blob: 67c78ce904adeabdbd342e2bb0ef416274ac84ca [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"
Alp Tokerb6cc5922014-05-03 03:45:55 +000028#include "clang/Basic/Builtins.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000030#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000031#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000032#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Parse/ParseDiagnostic.h"
37#include "clang/Sema/CXXFieldCollector.h"
38#include "clang/Sema/DeclSpec.h"
39#include "clang/Sema/DelayedDiagnostic.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000045#include "clang/Sema/Template.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000046#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000047#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000048#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000049#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000050#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000051using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000052using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000053
Richard Smithcd1c0552011-07-01 19:46:12 +000054Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 if (OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58 }
59
John McCall48871652010-08-21 09:40:31 +000060 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000061}
62
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000063namespace {
64
65class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66 public:
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000067 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68 bool AllowTemplates=false)
69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70 AllowClassTemplates(AllowTemplates) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000071 WantExpressionKeywords = false;
72 WantCXXNamedCasts = false;
73 WantRemainingKeywords = false;
74 }
75
Craig Toppere14c0f82014-03-12 04:55:44 +000076 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000077 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80 return (IsType || AllowedTemplate) &&
81 (AllowInvalidDecl || !ND->isInvalidDecl());
82 }
83 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000084 }
85
86 private:
87 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000088 bool WantClassName;
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000089 bool AllowClassTemplates;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000090};
91
92}
93
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +000094/// \brief Determine whether the token kind starts a simple-type-specifier.
95bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96 switch (Kind) {
97 // FIXME: Take into account the current language when deciding whether a
98 // token kind is a valid type specifier
99 case tok::kw_short:
100 case tok::kw_long:
101 case tok::kw___int64:
102 case tok::kw___int128:
103 case tok::kw_signed:
104 case tok::kw_unsigned:
105 case tok::kw_void:
106 case tok::kw_char:
107 case tok::kw_int:
108 case tok::kw_half:
109 case tok::kw_float:
110 case tok::kw_double:
111 case tok::kw_wchar_t:
112 case tok::kw_bool:
113 case tok::kw___underlying_type:
114 return true;
115
116 case tok::annot_typename:
117 case tok::kw_char16_t:
118 case tok::kw_char32_t:
119 case tok::kw_typeof:
David Majnemera5e92552013-09-22 01:24:26 +0000120 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +0000121 case tok::kw_decltype:
122 return getLangOpts().CPlusPlus;
123
124 default:
125 break;
126 }
127
128 return false;
129}
130
Douglas Gregorec6e1892009-02-04 19:16:12 +0000131/// \brief If the identifier refers to a type name within this scope,
132/// return the declaration of that type.
133///
134/// This routine performs ordinary name lookup of the identifier II
135/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000136/// determine whether the name refers to a type. If so, returns an
137/// opaque pointer (actually a QualType) corresponding to that
138/// type. Otherwise, returns NULL.
Dmitri Gribenko5267fdf2013-05-03 13:12:11 +0000139ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000140 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000141 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000142 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000143 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000144 bool WantNontrivialTypeSourceInfo,
145 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000146 // Determine where we will perform name lookup.
147 DeclContext *LookupCtx = 0;
148 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000149 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000150 if (ObjectType->isRecordType())
151 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000152 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000153 LookupCtx = computeDeclContext(*SS, false);
154
155 if (!LookupCtx) {
156 if (isDependentScopeSpecifier(*SS)) {
157 // C++ [temp.res]p3:
158 // A qualified-id that refers to a type and in which the
159 // nested-name-specifier depends on a template-parameter (14.6.2)
160 // shall be prefixed by the keyword typename to indicate that the
161 // qualified-id denotes a type, forming an
162 // elaborated-type-specifier (7.1.5.3).
163 //
164 // We therefore do not perform any name lookup if the result would
165 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000166 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000167 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000168
John McCallc392f372010-06-11 00:33:02 +0000169 // We know from the grammar that this name refers to a type,
170 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000171 if (WantNontrivialTypeSourceInfo)
172 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
173
174 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
Nico Weberdfc59202014-05-03 22:07:35 +0000175 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
176 II, NameLoc);
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(),
John Thompson2255f2c2014-04-23 12:57:01 +0000221 Kind, S, SS, Validator,
222 CTK_ErrorRecovery);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000223 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
224 TemplateTy Template;
225 bool MemberOfUnknownSpecialization;
226 UnqualifiedId TemplateName;
227 TemplateName.setIdentifier(NewII, NameLoc);
228 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
229 CXXScopeSpec NewSS, *NewSSPtr = SS;
230 if (SS && NNS) {
231 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 NewSSPtr = &NewSS;
233 }
234 if (Correction && (NNS || NewII != &II) &&
235 // Ignore a correction to a template type as the to-be-corrected
236 // identifier is not a template (typo correction for template names
237 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000238 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000239 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
240 false, Template, MemberOfUnknownSpecialization))) {
241 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
242 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000243 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000244 WantNontrivialTypeSourceInfo);
245 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000246 diagnoseTypo(Correction,
247 PDiag(diag::err_unknown_type_or_class_name_suggest)
248 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000249 if (SS && NNS)
250 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
251 *CorrectedII = NewII;
252 return Ty;
253 }
254 }
255 }
256 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000257 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000258 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000259 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000261
Chris Lattnere40853a2009-10-25 22:09:09 +0000262 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000263 // Recover from type-hiding ambiguities by hiding the type. We'll
264 // do the lookup again when looking for an object, and we can
265 // diagnose the error then. If we don't do this, then the error
266 // about hiding the type will be immediately followed by an error
267 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000268 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
269 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000270 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000271 }
John McCall6538c932009-10-10 05:48:19 +0000272
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000273 // Look to see if we have a type anywhere in the list of results.
274 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
275 Res != ResEnd; ++Res) {
276 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000277 if (!IIDecl ||
278 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000279 IIDecl->getLocation().getRawEncoding())
280 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000281 }
282 }
283
284 if (!IIDecl) {
285 // None of the entities we found is a type, so there is no way
286 // to even assume that the result is a type. In this case, don't
287 // complain about the ambiguity. The parser will either try to
288 // perform this lookup again (e.g., as an object name), which
289 // will produce the ambiguity, or will complain that it expected
290 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000291 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000292 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000293 }
294
295 // We found a type within the ambiguous lookup; diagnose the
296 // ambiguity and then return that type. This might be the right
297 // answer, or it might not be, but it suppresses any attempt to
298 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000299 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000300
Chris Lattnera3778332009-02-16 22:07:16 +0000301 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000302 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000303 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000304 }
305
Chris Lattner17e15f12009-10-25 17:16:46 +0000306 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000307
Chris Lattner17e15f12009-10-25 17:16:46 +0000308 QualType T;
309 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000310 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000311
Nico Weberdfc59202014-05-03 22:07:35 +0000312 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);
Aaron Ballman574705e2014-03-13 15:41:46 +0000389 for (const auto &Base : RD->bases())
390 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
Francois Pichet48c946e2011-04-13 02:38:49 +0000391 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000392 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000393 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000394 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000395}
396
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000397bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000398 SourceLocation IILoc,
399 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000400 CXXScopeSpec *SS,
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000401 ParsedType &SuggestedType,
402 bool AllowClassTemplates) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000403 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000404 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000405
Douglas Gregor2d435302009-12-30 17:04:44 +0000406 // There may have been a typo in the name of the type. Look up typo
407 // results, in case we have something that we can suggest.
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000408 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000409 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000410 LookupOrdinaryName, S, SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000411 Validator, CTK_ErrorRecovery)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000412 if (Corrected.isKeyword()) {
413 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000414 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
415 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000416 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000417 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000418 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000419 diagnoseTypo(Corrected,
420 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000421 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000422 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
423 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000424 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000425 diagnoseTypo(Corrected,
426 PDiag(diag::err_unknown_nested_typename_suggest)
427 << II << DC << DroppedSpecifier << SS->getRange());
428 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000429 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000430 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000431
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000432 CXXScopeSpec tmpSS;
433 if (Corrected.getCorrectionSpecifier())
434 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
435 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000436 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000437 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
438 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000439 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000440 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000441 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000442 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000443 }
444
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000446 // See if II is a class template that the user forgot to pass arguments to.
447 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000448 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000449 CXXScopeSpec EmptySS;
450 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000451 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000452 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000453 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000454 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000455 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000456 Diag(IILoc, diag::err_template_missing_args) << TplName;
457 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
458 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
459 << TplDecl->getTemplateParameters()->getSourceRange();
460 }
461 return true;
462 }
463 }
464
Douglas Gregor15e56022009-10-13 23:27:22 +0000465 // FIXME: Should we move the logic that tries to recover from a missing tag
466 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
467
Douglas Gregor2d435302009-12-30 17:04:44 +0000468 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000469 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000470 else if (DeclContext *DC = computeDeclContext(*SS, false))
471 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000472 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000473 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000474 unsigned DiagID = diag::err_typename_missing;
Alp Tokerbfa39342014-01-14 12:51:41 +0000475 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000476 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000477
478 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000479 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000480 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000481 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000482 SuggestedType = ActOnTypenameType(S, SourceLocation(),
483 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000484 } else {
485 assert(SS && SS->isInvalid() &&
486 "Invalid scope specifier has already been diagnosed");
487 }
488
489 return true;
490}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000491
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000492/// \brief Determine whether the given result set contains either a type name
493/// or
494static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000495 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000496 NextToken.is(tok::less);
497
498 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
499 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
500 return true;
501
502 if (CheckTemplate && isa<TemplateDecl>(*I))
503 return true;
504 }
505
506 return false;
507}
508
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000509static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
510 Scope *S, CXXScopeSpec &SS,
511 IdentifierInfo *&Name,
512 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000513 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
514 SemaRef.LookupParsedName(R, S, &SS);
515 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000516 const char *TagName = 0;
517 const char *FixItTagName = 0;
518 switch (Tag->getTagKind()) {
519 case TTK_Class:
520 TagName = "class";
521 FixItTagName = "class ";
522 break;
523
524 case TTK_Enum:
525 TagName = "enum";
526 FixItTagName = "enum ";
527 break;
528
529 case TTK_Struct:
530 TagName = "struct";
531 FixItTagName = "struct ";
532 break;
533
Joao Matosdc86f942012-08-31 18:45:21 +0000534 case TTK_Interface:
535 TagName = "__interface";
536 FixItTagName = "__interface ";
537 break;
538
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000539 case TTK_Union:
540 TagName = "union";
541 FixItTagName = "union ";
542 break;
543 }
544
545 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
546 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
547 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
548
Richard Smithaa31b4b2012-09-06 01:37:56 +0000549 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
550 I != IEnd; ++I)
551 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
552 << Name << TagName;
553
554 // Replace lookup results with just the tag decl.
555 Result.clear(Sema::LookupTagName);
556 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000557 return true;
558 }
559
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000560 return false;
561}
562
Richard Smith4f605af2012-08-18 00:55:03 +0000563/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
564static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
565 QualType T, SourceLocation NameLoc) {
566 ASTContext &Context = S.Context;
567
568 TypeLocBuilder Builder;
569 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
570
571 T = S.getElaboratedType(ETK_None, SS, T);
572 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
573 ElabTL.setElaboratedKeywordLoc(SourceLocation());
574 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
575 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
576}
577
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000578Sema::NameClassification Sema::ClassifyName(Scope *S,
579 CXXScopeSpec &SS,
580 IdentifierInfo *&Name,
581 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000582 const Token &NextToken,
583 bool IsAddressOfOperand,
584 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000585 DeclarationNameInfo NameInfo(Name, NameLoc);
586 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000587
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000588 if (NextToken.is(tok::coloncolon)) {
589 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
590 QualType(), false, SS, 0, false);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000591 }
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000592
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000593 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
594 LookupParsedName(Result, S, &SS, !CurMethod);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000595
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000596 // Perform lookup for Objective-C instance variables (including automatically
597 // synthesized instance variables), if we're in an Objective-C method.
598 // FIXME: This lookup really, really needs to be folded in to the normal
599 // unqualified lookup mechanism.
600 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
601 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000602 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000603 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000604 }
605
606 bool SecondTry = false;
607 bool IsFilteredTemplateName = false;
608
609Corrected:
610 switch (Result.getResultKind()) {
611 case LookupResult::NotFound:
612 // If an unqualified-id is followed by a '(', then we have a function
613 // call.
614 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
615 // In C++, this is an ADL-only call.
616 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000617 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000618 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
619
620 // C90 6.3.2.2:
621 // If the expression that precedes the parenthesized argument list in a
622 // function call consists solely of an identifier, and if no
623 // declaration is visible for this identifier, the identifier is
624 // implicitly declared exactly as if, in the innermost block containing
625 // the function call, the declaration
626 //
627 // extern int identifier ();
628 //
629 // appeared.
630 //
631 // We also allow this in C99 as an extension.
632 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
633 Result.addDecl(D);
634 Result.resolveKind();
635 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
636 }
637 }
638
639 // In C, we first see whether there is a tag type by the same name, in
640 // which case it's likely that the user just forget to write "enum",
641 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000642 if (!getLangOpts().CPlusPlus && !SecondTry &&
643 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
644 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000645 }
646
647 // Perform typo correction to determine if there is another name that is
648 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000649 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000650 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000651 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000652 Result.getLookupKind(), S,
John Thompson2255f2c2014-04-23 12:57:01 +0000653 &SS, *CCC,
654 CTK_ErrorRecovery)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000655 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
656 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000657
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000658 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000659 NamedDecl *UnderlyingFirstDecl
660 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000661 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000662 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000663 UnqualifiedDiag = diag::err_no_template_suggest;
664 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000665 } else if (UnderlyingFirstDecl &&
666 (isa<TypeDecl>(UnderlyingFirstDecl) ||
667 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
668 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000669 UnqualifiedDiag = diag::err_unknown_typename_suggest;
670 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
671 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000672
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000673 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000675 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000676 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
677 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000678 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000679 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
680 << Name << computeDeclContext(SS, false)
681 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000682 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000683
684 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000685 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000686
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000687 // Typo correction corrected to a keyword.
688 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000689 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000690
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000691 // Also update the LookupResult...
692 // FIXME: This should probably go away at some point
693 Result.clear();
694 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000695 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000696 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000697
698 // If we found an Objective-C instance variable, let
699 // LookupInObjCMethod build the appropriate expression to
700 // reference the ivar.
701 // FIXME: This is a gross hack.
702 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
703 Result.clear();
704 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000705 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000706 }
707
708 goto Corrected;
709 }
710 }
711
712 // We failed to correct; just fall through and let the parser deal with it.
713 Result.suppressDiagnostics();
714 return NameClassification::Unknown();
715
Abramo Bagnara7945c982012-01-27 09:46:47 +0000716 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000717 // We performed name lookup into the current instantiation, and there were
718 // dependent bases, so we treat this result the same way as any other
719 // dependent nested-name-specifier.
720
721 // C++ [temp.res]p2:
722 // A name used in a template declaration or definition and that is
723 // dependent on a template-parameter is assumed not to name a type
724 // unless the applicable name lookup finds a type name or the name is
725 // qualified by the keyword typename.
726 //
727 // FIXME: If the next token is '<', we might want to ask the parser to
728 // perform some heroics to see if we actually have a
729 // template-argument-list, which would indicate a missing 'template'
730 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000731 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
732 NameInfo, IsAddressOfOperand,
733 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000734 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000735
736 case LookupResult::Found:
737 case LookupResult::FoundOverloaded:
738 case LookupResult::FoundUnresolvedValue:
739 break;
740
741 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000742 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000743 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000744 // C++ [temp.local]p3:
745 // A lookup that finds an injected-class-name (10.2) can result in an
746 // ambiguity in certain cases (for example, if it is found in more than
747 // one base class). If all of the injected-class-names that are found
748 // refer to specializations of the same class template, and if the name
749 // is followed by a template-argument-list, the reference refers to the
750 // class template itself and not a specialization thereof, and is not
751 // ambiguous.
752 //
753 // This filtering can make an ambiguous result into an unambiguous one,
754 // so try again after filtering out template names.
755 FilterAcceptableTemplateNames(Result);
756 if (!Result.isAmbiguous()) {
757 IsFilteredTemplateName = true;
758 break;
759 }
760 }
761
762 // Diagnose the ambiguity and return an error.
763 return NameClassification::Error();
764 }
765
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000767 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
768 // C++ [temp.names]p3:
769 // After name lookup (3.4) finds that a name is a template-name or that
770 // an operator-function-id or a literal- operator-id refers to a set of
771 // overloaded functions any member of which is a function template if
772 // this is followed by a <, the < is always taken as the delimiter of a
773 // template-argument-list and never as the less-than operator.
774 if (!IsFilteredTemplateName)
775 FilterAcceptableTemplateNames(Result);
776
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000777 if (!Result.empty()) {
778 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000779 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000780 TemplateName Template;
781 if (Result.end() - Result.begin() > 1) {
782 IsFunctionTemplate = true;
783 Template = Context.getOverloadedTemplateName(Result.begin(),
784 Result.end());
785 } else {
786 TemplateDecl *TD
787 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
788 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000789 IsVarTemplate = isa<VarTemplateDecl>(TD);
790
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000791 if (SS.isSet() && !SS.isInvalid())
792 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000793 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000794 TD);
795 else
796 Template = TemplateName(TD);
797 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000798
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000799 if (IsFunctionTemplate) {
800 // Function templates always go through overload resolution, at which
801 // point we'll perform the various checks (e.g., accessibility) we need
802 // to based on which function we selected.
803 Result.suppressDiagnostics();
804
805 return NameClassification::FunctionTemplate(Template);
806 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000807
808 return IsVarTemplate ? NameClassification::VarTemplate(Template)
809 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000810 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000811 }
Richard Smith4f605af2012-08-18 00:55:03 +0000812
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000813 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000814 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
815 DiagnoseUseOfDecl(Type, NameLoc);
816 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000817 if (SS.isNotEmpty())
818 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000819 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000820 }
Richard Smith4f605af2012-08-18 00:55:03 +0000821
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000822 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
823 if (!Class) {
824 // FIXME: It's unfortunate that we don't have a Type node for handling this.
Nico Weberdfc59202014-05-03 22:07:35 +0000825 if (ObjCCompatibleAliasDecl *Alias =
826 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000827 Class = Alias->getClassInterface();
828 }
829
830 if (Class) {
831 DiagnoseUseOfDecl(Class, NameLoc);
832
833 if (NextToken.is(tok::period)) {
834 // Interface. <something> is parsed as a property reference expression.
835 // Just return "unknown" as a fall-through for now.
836 Result.suppressDiagnostics();
837 return NameClassification::Unknown();
838 }
839
840 QualType T = Context.getObjCInterfaceType(Class);
841 return ParsedType::make(T);
842 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000843
Richard Smith4f605af2012-08-18 00:55:03 +0000844 // We can have a type template here if we're classifying a template argument.
845 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
846 return NameClassification::TypeTemplate(
847 TemplateName(cast<TemplateDecl>(FirstDecl)));
848
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000849 // Check for a tag type hidden by a non-type decl in a few cases where it
850 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000851 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
852 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000853 (NextIsOp &&
854 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000855 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
856 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
857 DiagnoseUseOfDecl(Type, NameLoc);
858 QualType T = Context.getTypeDeclType(Type);
859 if (SS.isNotEmpty())
860 return buildNestedType(*this, SS, T, NameLoc);
861 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000862 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000863
Richard Smith4f605af2012-08-18 00:55:03 +0000864 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000865 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000866
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000867 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
868 return BuildDeclarationNameExpr(SS, Result, ADL);
869}
870
John McCall5ed6e8f2009-08-18 00:00:49 +0000871// Determines the context to return to after temporarily entering a
872// context. This depends in an unnecessarily complicated way on the
873// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000874DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000875
John McCall5ed6e8f2009-08-18 00:00:49 +0000876 // Functions defined inline within classes aren't parsed until we've
877 // finished parsing the top-level class, so the top-level class is
878 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000879 // A Lambda call operator whose parent is a class must not be treated
880 // as an inline member function. A Lambda can be used legally
881 // either as an in-class member initializer or a default argument. These
882 // are parsed once the class has been marked complete and so the containing
883 // context would be the nested class (when the lambda is defined in one);
884 // If the class is not complete, then the lambda is being used in an
885 // ill-formed fashion (such as to specify the width of a bit-field, or
886 // in an array-bound) - in which case we still want to return the
887 // lexically containing DC (which could be a nested class).
888 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000889 DC = DC->getLexicalParent();
890
891 // A function not defined within a class will always return to its
892 // lexical context.
893 if (!isa<CXXRecordDecl>(DC))
894 return DC;
895
896 // A C++ inline method/friend is parsed *after* the topmost class
897 // it was declared in is fully parsed ("complete"); the topmost
898 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000899 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000900 DC = RD;
901
902 // Return the declaration context of the topmost class the inline method is
903 // declared in.
904 return DC;
905 }
906
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000907 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000908}
909
Douglas Gregor91f84212008-12-11 16:49:14 +0000910void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000911 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000912 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000913 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000914 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000915}
916
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000917void Sema::PopDeclContext() {
918 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000919
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000920 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000921 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000922}
923
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000924/// EnterDeclaratorContext - Used when we must lookup names in the context
925/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000926///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000927void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000928 // C++0x [basic.lookup.unqual]p13:
929 // A name used in the definition of a static data member of class
930 // X (after the qualified-id of the static member) is looked up as
931 // if the name was used in a member function of X.
932 // C++0x [basic.lookup.unqual]p14:
933 // If a variable member of a namespace is defined outside of the
934 // scope of its namespace then any name used in the definition of
935 // the variable member (after the declarator-id) is looked up as
936 // if the definition of the variable member occurred in its
937 // namespace.
938 // Both of these imply that we should push a scope whose context
939 // is the semantic context of the declaration. We can't use
940 // PushDeclContext here because that context is not necessarily
941 // lexically contained in the current context. Fortunately,
942 // the containing scope should have the appropriate information.
943
944 assert(!S->getEntity() && "scope already has entity");
945
946#ifndef NDEBUG
947 Scope *Ancestor = S->getParent();
948 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
949 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
950#endif
951
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000953 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000954}
955
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000956void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000957 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000958
John McCall6df5fef2009-12-19 10:49:29 +0000959 // Switch back to the lexical context. The safety of this is
960 // enforced by an assert in EnterDeclaratorContext.
961 Scope *Ancestor = S->getParent();
962 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000963 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000964
965 // We don't need to do anything with the scope, which is going to
966 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000967}
968
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000969
970void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +0000971 // We assume that the caller has already called
972 // ActOnReenterTemplateScope so getTemplatedDecl() works.
973 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000974 if (!FD)
975 return;
976
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000977 // Same implementation as PushDeclContext, but enters the context
978 // from the lexical parent, rather than the top-level class.
979 assert(CurContext == FD->getLexicalParent() &&
980 "The next DeclContext should be lexically contained in the current one.");
981 CurContext = FD;
982 S->setEntity(CurContext);
983
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000984 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
985 ParmVarDecl *Param = FD->getParamDecl(P);
986 // If the parameter has an identifier, then add it to the scope
987 if (Param->getIdentifier()) {
988 S->AddDecl(Param);
989 IdResolver.AddDecl(Param);
990 }
991 }
992}
993
994
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000995void Sema::ActOnExitFunctionContext() {
996 // Same implementation as PopDeclContext, but returns to the lexical parent,
997 // rather than the top-level class.
998 assert(CurContext && "DeclContext imbalance!");
999 CurContext = CurContext->getLexicalParent();
1000 assert(CurContext && "Popped translation unit!");
1001}
1002
1003
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001004/// \brief Determine whether we allow overloading of the function
1005/// PrevDecl with another declaration.
1006///
1007/// This routine determines whether overloading is possible, not
1008/// whether some new function is actually an overload. It will return
1009/// true in C++ (where we can always provide overloads) or, as an
1010/// extension, in C when the previous function is already an
1011/// overloaded function declaration or has the "overloadable"
1012/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001013static bool AllowOverloadingOfFunction(LookupResult &Previous,
1014 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001015 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001016 return true;
1017
John McCall1f82f242009-11-18 22:49:29 +00001018 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001019 return true;
1020
John McCall1f82f242009-11-18 22:49:29 +00001021 return (Previous.getResultKind() == LookupResult::Found
1022 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001023}
1024
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001025/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001026void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001027 // Move up the scope chain until we find the nearest enclosing
1028 // non-transparent context. The declaration will be introduced into this
1029 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001030 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001031 S = S->getParent();
1032
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001033 // Add scoped declarations into their context, so that they can be
1034 // found later. Declarations without a context won't be inserted
1035 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001036 if (AddToContext)
1037 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001038
Richard Smith541b38b2013-09-20 01:15:31 +00001039 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1040 // are function-local declarations.
1041 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001042 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001043 D->getLexicalDeclContext()->getRedeclContext()) &&
1044 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001045 return;
1046
1047 // Template instantiations should also not be pushed into scope.
1048 if (isa<FunctionDecl>(D) &&
1049 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001050 return;
1051
John McCall9f3059a2009-10-09 21:13:30 +00001052 // If this replaces anything in the current scope,
1053 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1054 IEnd = IdResolver.end();
1055 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001056 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1057 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001058 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001059
John McCall9f3059a2009-10-09 21:13:30 +00001060 // Should only need to replace one decl.
1061 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001062 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001063 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064
John McCall48871652010-08-21 09:40:31 +00001065 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001066
1067 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1068 // Implicitly-generated labels may end up getting generated in an order that
1069 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1070 // the label at the appropriate place in the identifier chain.
1071 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001072 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001073 if (IDC == CurContext) {
1074 if (!S->isDeclScope(*I))
1075 continue;
1076 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001077 break;
1078 }
1079
Douglas Gregor46c04e72011-03-16 16:39:03 +00001080 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001081 } else {
1082 IdResolver.AddDecl(D);
1083 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001084}
1085
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001086void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1087 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1088 TUScope->AddDecl(D);
1089}
1090
Richard Smith1c34fb72013-08-13 18:18:50 +00001091bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001092 bool AllowInlineNamespace) {
1093 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001094}
1095
John McCallcc14d1f2010-08-24 08:50:51 +00001096Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1097 DeclContext *TargetDC = DC->getPrimaryContext();
1098 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001099 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001100 if (ScopeDC->getPrimaryContext() == TargetDC)
1101 return S;
1102 } while ((S = S->getParent()));
1103
1104 return 0;
1105}
1106
John McCall1f82f242009-11-18 22:49:29 +00001107static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1108 DeclContext*,
1109 ASTContext&);
1110
1111/// Filters out lookup results that don't fall within the given scope
1112/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001113void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001114 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001115 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001116 LookupResult::Filter F = R.makeFilter();
1117 while (F.hasNext()) {
1118 NamedDecl *D = F.next();
1119
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001121 continue;
1122
Richard Smith72bcaec2013-12-05 04:30:04 +00001123 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001124 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001125
John McCall1f82f242009-11-18 22:49:29 +00001126 F.erase();
1127 }
1128
1129 F.done();
1130}
1131
1132static bool isUsingDecl(NamedDecl *D) {
1133 return isa<UsingShadowDecl>(D) ||
1134 isa<UnresolvedUsingTypenameDecl>(D) ||
1135 isa<UnresolvedUsingValueDecl>(D);
1136}
1137
1138/// Removes using shadow declarations from the lookup results.
1139static void RemoveUsingDecls(LookupResult &R) {
1140 LookupResult::Filter F = R.makeFilter();
1141 while (F.hasNext())
1142 if (isUsingDecl(F.next()))
1143 F.erase();
1144
1145 F.done();
1146}
1147
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001148/// \brief Check for this common pattern:
1149/// @code
1150/// class S {
1151/// S(const S&); // DO NOT IMPLEMENT
1152/// void operator=(const S&); // DO NOT IMPLEMENT
1153/// };
1154/// @endcode
1155static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1156 // FIXME: Should check for private access too but access is set after we get
1157 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001158 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001159 return false;
1160
1161 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1162 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1164 return Method->isCopyAssignmentOperator();
1165 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001166}
1167
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001168// We need this to handle
1169//
1170// typedef struct {
1171// void *foo() { return 0; }
1172// } A;
1173//
1174// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1175// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001176// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001177// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001178// Callers should verify at the end of the TU if it D has external linkage or
1179// not.
1180bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1181 const DeclContext *DC = D->getDeclContext();
1182 while (!DC->isTranslationUnit()) {
1183 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1184 if (!RD->hasNameForLinkage())
1185 return true;
1186 }
1187 DC = DC->getParent();
1188 }
1189
Rafael Espindola3ae00052013-05-13 00:12:11 +00001190 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001191}
1192
Eli Friedman5ef21752013-09-10 03:05:56 +00001193// FIXME: This needs to be refactored; some other isInMainFile users want
1194// these semantics.
1195static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1196 if (S.TUKind != TU_Complete)
1197 return false;
1198 return S.SourceMgr.isInMainFile(Loc);
1199}
1200
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001201bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1202 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001203
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001204 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1205 return false;
1206
Richard Smithc3926172014-04-02 18:28:36 +00001207 // Ignore all entities declared within templates, and out-of-line definitions
1208 // of members of 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.
Richard Smitha90ee352014-05-11 21:25:24 +00001222 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001223 return false;
1224 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001225
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001226 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001227 Context.DeclMustBeEmitted(FD))
1228 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001229 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001230 // Constants and utility variables are defined in headers with internal
1231 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1232 // like "inline".)
1233 if (!isMainFileLoc(*this, VD->getLocation()))
1234 return false;
1235
Eli Friedman5ef21752013-09-10 03:05:56 +00001236 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001237 return false;
1238
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001239 if (VD->isStaticDataMember() &&
1240 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1241 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001242 } else {
1243 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001244 }
1245
John McCalld37d35b2010-10-27 01:41:35 +00001246 // Only warn for unused decls internal to the translation unit.
Richard Smitha90ee352014-05-11 21:25:24 +00001247 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1248 // for inline functions defined in the main source file, for instance.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001249 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001250}
1251
1252void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (!D)
1254 return;
1255
1256 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001257 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001258 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1259 return; // First should already be in the vector.
1260 }
1261
1262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001263 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001264 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1265 return; // First should already be in the vector.
1266 }
1267
David Blaikie3d8edc22012-05-26 05:35:39 +00001268 if (ShouldWarnIfUnusedFileScopedDecl(D))
1269 UnusedFileScopedDecls.push_back(D);
1270}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001271
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001272static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001273 if (D->isInvalidDecl())
1274 return false;
1275
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001276 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1277 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001278 return false;
John McCall67da35c2010-02-04 22:26:26 +00001279
Chris Lattnercab02a62011-02-17 20:34:02 +00001280 if (isa<LabelDecl>(D))
1281 return true;
1282
John McCall67da35c2010-02-04 22:26:26 +00001283 // White-list anything that isn't a local variable.
1284 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1285 !D->getDeclContext()->isFunctionOrMethod())
1286 return false;
1287
1288 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001289 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001290
1291 // White-list anything with an __attribute__((unused)) type.
1292 QualType Ty = VD->getType();
1293
1294 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001295 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001296 if (TT->getDecl()->hasAttr<UnusedAttr>())
1297 return false;
1298 }
1299
Douglas Gregor14f232e2010-05-08 23:05:03 +00001300 // If we failed to complete the type for some reason, or if the type is
1301 // dependent, don't diagnose the variable.
1302 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001303 return false;
1304
John McCallcef15822010-03-31 02:47:45 +00001305 if (const TagType *TT = Ty->getAs<TagType>()) {
1306 const TagDecl *Tag = TT->getDecl();
1307 if (Tag->hasAttr<UnusedAttr>())
1308 return false;
1309
1310 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001311 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001312 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001313
1314 if (const Expr *Init = VD->getInit()) {
Nico Weberdfc59202014-05-03 22:07:35 +00001315 if (const ExprWithCleanups *Cleanups =
1316 dyn_cast<ExprWithCleanups>(Init))
David Blaikiea9d4a932012-10-24 21:29:06 +00001317 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001318 const CXXConstructExpr *Construct =
1319 dyn_cast<CXXConstructExpr>(Init);
1320 if (Construct && !Construct->isElidable()) {
1321 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001322 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001323 return false;
1324 }
1325 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001326 }
1327 }
John McCallcef15822010-03-31 02:47:45 +00001328
1329 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001330 }
1331
John McCall67da35c2010-02-04 22:26:26 +00001332 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001333}
1334
Anna Zaks964f4c62011-07-28 20:52:06 +00001335static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1336 FixItHint &Hint) {
1337 if (isa<LabelDecl>(D)) {
1338 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001339 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001340 if (AfterColon.isInvalid())
1341 return;
1342 Hint = FixItHint::CreateRemoval(CharSourceRange::
1343 getCharRange(D->getLocStart(), AfterColon));
1344 }
1345 return;
1346}
1347
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001348/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1349/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001350void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1351 if (!ShouldDiagnoseUnusedDecl(D))
1352 return;
1353
Nico Weberdfc59202014-05-03 22:07:35 +00001354 FixItHint Hint;
Anna Zaks964f4c62011-07-28 20:52:06 +00001355 GenerateFixForUnusedDecl(D, Context, Hint);
1356
Chris Lattnercab02a62011-02-17 20:34:02 +00001357 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001358 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001359 DiagID = diag::warn_unused_exception_param;
1360 else if (isa<LabelDecl>(D))
1361 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001362 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001363 DiagID = diag::warn_unused_variable;
1364
Anna Zaks964f4c62011-07-28 20:52:06 +00001365 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001366}
1367
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001368static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1369 // Verify that we have no forward references left. If so, there was a goto
1370 // or address of a label taken, but no definition of it. Label fwd
1371 // definitions are indicated with a null substmt.
1372 if (L->getStmt() == 0)
1373 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1374}
1375
Steve Naroffc62adb62007-10-09 22:01:59 +00001376void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00001377 S->mergeNRVOIntoParent();
1378
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001379 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001380 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001381 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001382
Aaron Ballman35c54952014-03-17 16:55:25 +00001383 for (auto *TmpD : S->decls()) {
Steve Naroff9324db12007-09-13 18:10:37 +00001384 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001385
Douglas Gregor91f84212008-12-11 16:49:14 +00001386 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1387 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001388
Douglas Gregor91f84212008-12-11 16:49:14 +00001389 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001390
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001391 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001392 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001393 DiagnoseUnusedDecl(D);
1394
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001395 // If this was a forward reference to a label, verify it was defined.
1396 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1397 CheckPoppedLabel(LD, *this);
1398
Douglas Gregor91f84212008-12-11 16:49:14 +00001399 // Remove this name from our lexical scope.
1400 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001401 }
1402}
1403
Douglas Gregor1c283312010-08-11 12:19:30 +00001404/// \brief Look for an Objective-C class in the translation unit.
1405///
1406/// \param Id The name of the Objective-C class we're looking for. If
1407/// typo-correction fixes this name, the Id will be updated
1408/// to the fixed name.
1409///
1410/// \param IdLoc The location of the name in the translation unit.
1411///
James Dennett41725122012-06-22 10:16:05 +00001412/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001413/// if there is no class with the given name.
1414///
1415/// \returns The declaration of the named Objective-C class, or NULL if the
1416/// class could not be found.
1417ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1418 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001419 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001420 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1421 // creation from this context.
1422 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1423
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001424 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001425 // Perform typo correction at the given location, but only if we
1426 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001427 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1428 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1429 LookupOrdinaryName, TUScope, NULL,
John Thompson2255f2c2014-04-23 12:57:01 +00001430 Validator, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001431 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001432 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001433 Id = IDecl->getIdentifier();
1434 }
1435 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001436 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1437 // This routine must always return a class definition, if any.
1438 if (Def && Def->getDefinition())
1439 Def = Def->getDefinition();
1440 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001441}
1442
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001443/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1444/// from S, where a non-field would be declared. This routine copes
1445/// with the difference between C and C++ scoping rules in structs and
1446/// unions. For example, the following code is well-formed in C but
1447/// ill-formed in C++:
1448/// @code
1449/// struct S6 {
1450/// enum { BAR } e;
1451/// };
Mike Stump11289f42009-09-09 15:08:12 +00001452///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001453/// void test_S6() {
1454/// struct S6 a;
1455/// a.e = BAR;
1456/// }
1457/// @endcode
1458/// For the declaration of BAR, this routine will return a different
1459/// scope. The scope S will be the scope of the unnamed enumeration
1460/// within S6. In C++, this routine will return the scope associated
1461/// with S6, because the enumeration's scope is a transparent
1462/// context but structures can contain non-field names. In C, this
1463/// routine will return the translation unit scope, since the
1464/// enumeration's scope is a transparent context and structures cannot
1465/// contain non-field names.
1466Scope *Sema::getNonFieldDeclScope(Scope *S) {
1467 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001468 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001469 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001470 S = S->getParent();
1471 return S;
1472}
1473
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001474/// \brief Looks up the declaration of "struct objc_super" and
1475/// saves it for later use in building builtin declaration of
1476/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1477/// pre-existing declaration exists no action takes place.
1478static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1479 IdentifierInfo *II) {
1480 if (!II->isStr("objc_msgSendSuper"))
1481 return;
1482 ASTContext &Context = ThisSema.Context;
1483
1484 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1485 SourceLocation(), Sema::LookupTagName);
1486 ThisSema.LookupName(Result, S);
1487 if (Result.getResultKind() == LookupResult::Found)
1488 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1489 Context.setObjCSuperType(Context.getTagDeclType(TD));
1490}
1491
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001492/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1493/// file scope. lazily create a decl for it. ForRedeclaration is true
1494/// if we're creating this built-in in anticipation of redeclaring the
1495/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001496NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001497 Scope *S, bool ForRedeclaration,
1498 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001499 LookupPredefedObjCSuperType(*this, S, II);
1500
Chris Lattner9561a0b2007-01-28 08:20:04 +00001501 Builtin::ID BID = (Builtin::ID)bid;
1502
Chris Lattnerecd79c62009-06-14 00:45:47 +00001503 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001504 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001505 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001506 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001507 // Okay
1508 break;
1509
Mike Stump93246cc2009-07-28 23:57:15 +00001510 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001511 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001512 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001513 << Context.BuiltinInfo.GetName(BID);
1514 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001515
Mike Stump93246cc2009-07-28 23:57:15 +00001516 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001517 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001518 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001519 << Context.BuiltinInfo.GetName(BID);
1520 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001521
1522 case ASTContext::GE_Missing_ucontext:
1523 if (ForRedeclaration)
1524 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1525 << Context.BuiltinInfo.GetName(BID);
1526 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001527 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001528
1529 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1530 Diag(Loc, diag::ext_implicit_lib_function_decl)
1531 << Context.BuiltinInfo.GetName(BID)
1532 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001533 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001534 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001535 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001536 Diag(Loc, diag::note_please_include_header)
1537 << Context.BuiltinInfo.getHeaderName(BID)
1538 << Context.BuiltinInfo.GetName(BID);
1539 }
1540
Warren Hunt445d83e2013-11-01 23:46:51 +00001541 DeclContext *Parent = Context.getTranslationUnitDecl();
1542 if (getLangOpts().CPlusPlus) {
1543 LinkageSpecDecl *CLinkageDecl =
1544 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1545 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001546 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001547 Parent->addDecl(CLinkageDecl);
1548 Parent = CLinkageDecl;
1549 }
1550
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001551 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001552 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001553 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001554 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001555 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001556 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001557 New->setImplicit();
1558
Chris Lattner4dd27102008-05-05 22:18:14 +00001559 // Create Decl objects for each parameter, adding them to the
1560 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001561 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001562 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001563 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001564 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001565 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1566 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001567 parm->setScopeInfo(0, i);
1568 Params.push_back(parm);
1569 }
David Blaikie9c70e042011-09-21 18:16:56 +00001570 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
1573 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001574 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001576 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001577 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1578 // relate Scopes to DeclContexts, and probably eliminate CurContext
1579 // entirely, but we're not there yet.
1580 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001581 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001582 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001583 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001584 return New;
1585}
1586
Douglas Gregor3552dab2013-01-09 00:47:56 +00001587/// \brief Filter out any previous declarations that the given declaration
1588/// should not consider because they are not permitted to conflict, e.g.,
1589/// because they come from hidden sub-modules and do not refer to the same
1590/// entity.
1591static void filterNonConflictingPreviousDecls(ASTContext &context,
1592 NamedDecl *decl,
1593 LookupResult &previous){
1594 // This is only interesting when modules are enabled.
1595 if (!context.getLangOpts().Modules)
1596 return;
1597
1598 // Empty sets are uninteresting.
1599 if (previous.empty())
1600 return;
1601
Douglas Gregor3552dab2013-01-09 00:47:56 +00001602 LookupResult::Filter filter = previous.makeFilter();
1603 while (filter.hasNext()) {
1604 NamedDecl *old = filter.next();
1605
1606 // Non-hidden declarations are never ignored.
1607 if (!old->isHidden())
1608 continue;
1609
Rafael Espindola3ae00052013-05-13 00:12:11 +00001610 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001611 filter.erase();
1612 }
1613
1614 filter.done();
1615}
1616
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001617bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1618 QualType OldType;
1619 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1620 OldType = OldTypedef->getUnderlyingType();
1621 else
1622 OldType = Context.getTypeDeclType(Old);
1623 QualType NewType = New->getUnderlyingType();
1624
Douglas Gregoraab36982012-01-11 22:33:48 +00001625 if (NewType->isVariablyModifiedType()) {
1626 // Must not redefine a typedef with a variably-modified type.
1627 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1628 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1629 << Kind << NewType;
1630 if (Old->getLocation().isValid())
1631 Diag(Old->getLocation(), diag::note_previous_definition);
1632 New->setInvalidDecl();
1633 return true;
1634 }
1635
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001636 if (OldType != NewType &&
1637 !OldType->isDependentType() &&
1638 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001639 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001640 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1641 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1642 << Kind << NewType << OldType;
1643 if (Old->getLocation().isValid())
1644 Diag(Old->getLocation(), diag::note_previous_definition);
1645 New->setInvalidDecl();
1646 return true;
1647 }
1648 return false;
1649}
1650
Richard Smithdda56e42011-04-15 14:24:37 +00001651/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001652/// same name and scope as a previous declaration 'Old'. Figure out
1653/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001654/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001655///
Richard Smithdda56e42011-04-15 14:24:37 +00001656void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001657 // If the new decl is known invalid already, don't bother doing any
1658 // merging checks.
1659 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001660
Steve Naroff44cfcb62008-09-09 14:32:20 +00001661 // Allow multiple definitions for ObjC built-in typedefs.
1662 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001663 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001664 const IdentifierInfo *TypeID = New->getIdentifier();
1665 switch (TypeID->getLength()) {
1666 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001667 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001668 {
1669 if (!TypeID->isStr("id"))
1670 break;
1671 QualType T = New->getUnderlyingType();
1672 if (!T->isPointerType())
1673 break;
1674 if (!T->isVoidPointerType()) {
1675 QualType PT = T->getAs<PointerType>()->getPointeeType();
1676 if (!PT->isStructureType())
1677 break;
1678 }
1679 Context.setObjCIdRedefinitionType(T);
1680 // Install the built-in type for 'id', ignoring the current definition.
1681 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1682 return;
1683 }
Chris Lattner66e32812008-11-20 05:41:43 +00001684 case 5:
1685 if (!TypeID->isStr("Class"))
1686 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001687 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001688 // Install the built-in type for 'Class', ignoring the current definition.
1689 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001690 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001691 case 3:
1692 if (!TypeID->isStr("SEL"))
1693 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001694 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001695 // Install the built-in type for 'SEL', ignoring the current definition.
1696 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001697 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001698 }
1699 // Fall through - the typedef name was not a builtin type.
1700 }
John McCall1f82f242009-11-18 22:49:29 +00001701
Douglas Gregorfb034662009-01-28 17:15:10 +00001702 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001703 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1704 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001705 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001706 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001707
1708 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001709 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001710 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001711
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001712 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001713 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001714
John McCall1f82f242009-11-18 22:49:29 +00001715 // If the old declaration is invalid, just give up here.
1716 if (Old->isInvalidDecl())
1717 return New->setInvalidDecl();
1718
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001719 // If the typedef types are not identical, reject them in all languages and
1720 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001721 if (isIncompatibleTypedef(Old, New))
1722 return;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001724 // The types match. Link up the redeclaration chain and merge attributes if
1725 // the old declaration was a typedef.
1726 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001727 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001728 mergeDeclAttributes(New, Old);
1729 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001730
David Blaikiebbafb8a2012-03-11 07:00:24 +00001731 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001732 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001733
David Blaikiebbafb8a2012-03-11 07:00:24 +00001734 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001735 // C++ [dcl.typedef]p2:
1736 // In a given non-class scope, a typedef specifier can be used to
1737 // redefine the name of any type declared in that scope to refer
1738 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001739 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001740 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001741
1742 // C++0x [dcl.typedef]p4:
1743 // In a given class scope, a typedef specifier can be used to redefine
1744 // any class-name declared in that scope that is not also a typedef-name
1745 // to refer to the type to which it already refers.
1746 //
1747 // This wording came in via DR424, which was a correction to the
1748 // wording in DR56, which accidentally banned code like:
1749 //
1750 // struct S {
1751 // typedef struct A { } A;
1752 // };
1753 //
1754 // in the C++03 standard. We implement the C++0x semantics, which
1755 // allow the above but disallow
1756 //
1757 // struct S {
1758 // typedef int I;
1759 // typedef int I;
1760 // };
1761 //
1762 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001763 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001764 return;
1765
Chris Lattner2581fc32009-04-17 22:04:20 +00001766 Diag(New->getLocation(), diag::err_redefinition)
1767 << New->getDeclName();
1768 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001769 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001770 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001771
Douglas Gregor7363fb02012-01-11 04:25:01 +00001772 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001773 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001774 return;
1775
Chris Lattner2581fc32009-04-17 22:04:20 +00001776 // If we have a redefinition of a typedef in C, emit a warning. This warning
1777 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001778 // -Wtypedef-redefinition. If either the original or the redefinition is
1779 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001780 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001781 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1782 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001783 return;
Mike Stump11289f42009-09-09 15:08:12 +00001784
Chris Lattner2581fc32009-04-17 22:04:20 +00001785 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1786 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001787 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001788 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001789}
1790
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001791/// DeclhasAttr - returns true if decl Declaration already has the target
1792/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001793static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001794 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001795 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001796 for (const auto *i : D->attrs())
1797 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001798 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001799 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001800 return true;
1801 continue;
1802 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001803 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001804 if (OA && isa<OwnershipAttr>(i))
1805 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001806 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001807 }
Chris Lattner84966392008-03-03 03:28:21 +00001808
1809 return false;
1810}
1811
Richard Smithbc8caaf2013-02-22 04:55:39 +00001812static bool isAttributeTargetADefinition(Decl *D) {
1813 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1814 return VD->isThisDeclarationADefinition();
1815 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1816 return TD->isCompleteDefinition() || TD->isBeingDefined();
1817 return true;
1818}
1819
1820/// Merge alignment attributes from \p Old to \p New, taking into account the
1821/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1822///
1823/// \return \c true if any attributes were added to \p New.
1824static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1825 // Look for alignas attributes on Old, and pick out whichever attribute
1826 // specifies the strictest alignment requirement.
1827 AlignedAttr *OldAlignasAttr = 0;
1828 AlignedAttr *OldStrictestAlignAttr = 0;
1829 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001830 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001831 // FIXME: We have no way of representing inherited dependent alignments
1832 // in a case like:
1833 // template<int A, int B> struct alignas(A) X;
1834 // template<int A, int B> struct alignas(B) X {};
1835 // For now, we just ignore any alignas attributes which are not on the
1836 // definition in such a case.
1837 if (I->isAlignmentDependent())
1838 return false;
1839
1840 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001841 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001842
1843 unsigned Align = I->getAlignment(S.Context);
1844 if (Align > OldAlign) {
1845 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001846 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001847 }
1848 }
1849
1850 // Look for alignas attributes on New.
1851 AlignedAttr *NewAlignasAttr = 0;
1852 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001853 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001854 if (I->isAlignmentDependent())
1855 return false;
1856
1857 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001858 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001859
1860 unsigned Align = I->getAlignment(S.Context);
1861 if (Align > NewAlign)
1862 NewAlign = Align;
1863 }
1864
1865 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1866 // Both declarations have 'alignas' attributes. We require them to match.
1867 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1868 // fall short. (If two declarations both have alignas, they must both match
1869 // every definition, and so must match each other if there is a definition.)
1870
1871 // If either declaration only contains 'alignas(0)' specifiers, then it
1872 // specifies the natural alignment for the type.
1873 if (OldAlign == 0 || NewAlign == 0) {
1874 QualType Ty;
1875 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1876 Ty = VD->getType();
1877 else
1878 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1879
1880 if (OldAlign == 0)
1881 OldAlign = S.Context.getTypeAlign(Ty);
1882 if (NewAlign == 0)
1883 NewAlign = S.Context.getTypeAlign(Ty);
1884 }
1885
1886 if (OldAlign != NewAlign) {
1887 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1888 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1889 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1890 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1891 }
1892 }
1893
1894 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1895 // C++11 [dcl.align]p6:
1896 // if any declaration of an entity has an alignment-specifier,
1897 // every defining declaration of that entity shall specify an
1898 // equivalent alignment.
1899 // C11 6.7.5/7:
1900 // If the definition of an object does not have an alignment
1901 // specifier, any other declaration of that object shall also
1902 // have no alignment specifier.
1903 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001904 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001905 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001906 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001907 }
1908
1909 bool AnyAdded = false;
1910
1911 // Ensure we have an attribute representing the strictest alignment.
1912 if (OldAlign > NewAlign) {
1913 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1914 Clone->setInherited(true);
1915 New->addAttr(Clone);
1916 AnyAdded = true;
1917 }
1918
1919 // Ensure we have an alignas attribute if the old declaration had one.
1920 if (OldAlignasAttr && !NewAlignasAttr &&
1921 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1922 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1923 Clone->setInherited(true);
1924 New->addAttr(Clone);
1925 AnyAdded = true;
1926 }
1927
1928 return AnyAdded;
1929}
1930
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001931static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
1932 const InheritableAttr *Attr, bool Override) {
1933 InheritableAttr *NewAttr = nullptr;
Michael Han99315932013-01-24 16:46:58 +00001934 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001935 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001936 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1937 AA->getIntroduced(), AA->getDeprecated(),
1938 AA->getObsoleted(), AA->getUnavailable(),
1939 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001940 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001941 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001942 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1943 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001944 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001945 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1946 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001947 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001948 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1949 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001950 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001951 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1952 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001953 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001954 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1955 FA->getFormatIdx(), FA->getFirstArg(),
1956 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001957 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001958 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1959 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001960 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00001961 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1962 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00001963 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00001964 else if (isa<AlignedAttr>(Attr))
1965 // AlignedAttrs are handled separately, because we need to handle all
1966 // such attributes on a declaration at the same time.
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001967 NewAttr = nullptr;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001968 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001969 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001970
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001971 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001972 NewAttr->setInherited(true);
1973 D->addAttr(NewAttr);
1974 return true;
1975 }
1976
1977 return false;
1978}
1979
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001980static const Decl *getDefinition(const Decl *D) {
1981 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001982 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001983 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1984 const VarDecl *Def = VD->getDefinition();
1985 if (Def)
1986 return Def;
1987 return VD->getActingDefinition();
1988 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001990 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001991 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001992 return Def;
1993 }
1994 return NULL;
1995}
1996
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001997static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001998 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001999 if (Attribute->getKind() == Kind)
2000 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002001 return false;
2002}
2003
2004/// checkNewAttributesAfterDef - If we already have a definition, check that
2005/// there are no new attributes in this declaration.
2006static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2007 if (!New->hasAttrs())
2008 return;
2009
2010 const Decl *Def = getDefinition(Old);
2011 if (!Def || Def == New)
2012 return;
2013
2014 AttrVec &NewAttributes = New->getAttrs();
2015 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2016 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002017
2018 if (isa<AliasAttr>(NewAttribute)) {
2019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2020 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2021 else {
2022 VarDecl *VD = cast<VarDecl>(New);
2023 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2024 VarDecl::TentativeDefinition
2025 ? diag::err_alias_after_tentative
2026 : diag::err_redefinition;
2027 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2028 S.Diag(Def->getLocation(), diag::note_previous_definition);
2029 VD->setInvalidDecl();
2030 }
2031 ++I;
2032 continue;
2033 }
2034
2035 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2036 // Tentative definitions are only interesting for the alias check above.
2037 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2038 ++I;
2039 continue;
2040 }
2041 }
2042
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002043 if (hasAttribute(Def, NewAttribute->getKind())) {
2044 ++I;
2045 continue; // regular attr merging will take care of validating this.
2046 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002047
Richard Smithdebc59d2013-01-30 05:45:05 +00002048 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002049 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002050 ++I;
2051 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002052 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2053 if (AA->isAlignas()) {
2054 // C++11 [dcl.align]p6:
2055 // if any declaration of an entity has an alignment-specifier,
2056 // every defining declaration of that entity shall specify an
2057 // equivalent alignment.
2058 // C11 6.7.5/7:
2059 // If the definition of an object does not have an alignment
2060 // specifier, any other declaration of that object shall also
2061 // have no alignment specifier.
2062 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002063 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002064 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002065 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002066 NewAttributes.erase(NewAttributes.begin() + I);
2067 --E;
2068 continue;
2069 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002070 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002071
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002072 S.Diag(NewAttribute->getLocation(),
2073 diag::warn_attribute_precede_definition);
2074 S.Diag(Def->getLocation(), diag::note_previous_definition);
2075 NewAttributes.erase(NewAttributes.begin() + I);
2076 --E;
2077 }
2078}
2079
John McCallf79e87d2011-03-02 04:00:57 +00002080/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002081void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002082 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002083 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2084 UsedAttr *NewAttr = OldAttr->clone(Context);
2085 NewAttr->setInherited(true);
2086 New->addAttr(NewAttr);
2087 }
2088
Richard Smithe233fbf2013-01-28 22:42:45 +00002089 if (!Old->hasAttrs() && !New->hasAttrs())
2090 return;
2091
Rafael Espindola36191042012-05-18 01:47:00 +00002092 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002093 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002094
Douglas Gregor32c17572012-01-01 20:30:41 +00002095 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002096 return;
John McCallf79e87d2011-03-02 04:00:57 +00002097
Douglas Gregor32c17572012-01-01 20:30:41 +00002098 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002099
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002100 // Ensure that any moving of objects within the allocated map is done before
2101 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002102 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002103
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002104 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002105 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002106 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002107 if (isa<DeprecatedAttr>(I) ||
2108 isa<UnavailableAttr>(I) ||
2109 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002110 switch (AMK) {
2111 case AMK_None:
2112 continue;
John McCalld2930c22011-07-22 02:45:48 +00002113
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002114 case AMK_Redeclaration:
2115 break;
2116
2117 case AMK_Override:
2118 Override = true;
2119 break;
2120 }
2121 }
2122
Rafael Espindolab0938852013-10-25 01:28:12 +00002123 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002124 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002125 continue;
2126
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002127 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002128 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002129 }
John McCallf79e87d2011-03-02 04:00:57 +00002130
Richard Smithbc8caaf2013-02-22 04:55:39 +00002131 if (mergeAlignedAttrs(*this, New, Old))
2132 foundAny = true;
2133
Douglas Gregor32c17572012-01-01 20:30:41 +00002134 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002135}
2136
2137/// mergeParamDeclAttributes - Copy attributes from the old parameter
2138/// to the new one.
2139static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2140 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002141 Sema &S) {
2142 // C++11 [dcl.attr.depend]p2:
2143 // The first declaration of a function shall specify the
2144 // carries_dependency attribute for its declarator-id if any declaration
2145 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002146 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2147 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2148 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002149 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2150 // Find the first declaration of the parameter.
2151 // FIXME: Should we build redeclaration chains for function parameters?
2152 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002153 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002154 const ParmVarDecl *FirstVD =
2155 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2156 S.Diag(FirstVD->getLocation(),
2157 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2158 }
2159
John McCallf79e87d2011-03-02 04:00:57 +00002160 if (!oldDecl->hasAttrs())
2161 return;
2162
2163 bool foundAny = newDecl->hasAttrs();
2164
2165 // Ensure that any moving of objects within the allocated map is
2166 // done before we process them.
2167 if (!foundAny) newDecl->setAttrs(AttrVec());
2168
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002169 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2170 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002171 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002172 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002173 newAttr->setInherited(true);
2174 newDecl->addAttr(newAttr);
2175 foundAny = true;
2176 }
2177 }
2178
2179 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002180}
2181
Dan Gohman28ade552010-07-26 21:25:24 +00002182namespace {
2183
Douglas Gregora74a2972009-03-06 22:43:54 +00002184/// Used in MergeFunctionDecl to keep track of function parameters in
2185/// C.
2186struct GNUCompatibleParamWarning {
2187 ParmVarDecl *OldParm;
2188 ParmVarDecl *NewParm;
2189 QualType PromotedType;
2190};
2191
Dan Gohman28ade552010-07-26 21:25:24 +00002192}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002193
2194/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002195Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002196 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002197 if (Ctor->isDefaultConstructor())
2198 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002199
2200 if (Ctor->isCopyConstructor())
2201 return Sema::CXXCopyConstructor;
2202
2203 if (Ctor->isMoveConstructor())
2204 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002205 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002206 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002207 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002208 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002209 } else if (MD->isMoveAssignmentOperator()) {
2210 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002211 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002212
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002213 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002214}
2215
Sebastian Redl243d9052010-06-09 21:17:41 +00002216/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002217/// only extern inline functions can be redefined, and even then only in
2218/// GNU89 mode.
2219static bool canRedefineFunction(const FunctionDecl *FD,
2220 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002221 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2222 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002223 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002224 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002225}
2226
Reid Kleckner78af0702013-08-27 23:08:25 +00002227const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2228 const AttributedType *AT = T->getAs<AttributedType>();
2229 while (AT && !AT->isCallingConv())
2230 AT = AT->getModifiedType()->getAs<AttributedType>();
2231 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002232}
2233
Benjamin Kramer3e350262013-02-15 12:30:38 +00002234template <typename T>
2235static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002236 const DeclContext *DC = Old->getDeclContext();
2237 if (DC->isRecord())
2238 return false;
2239
2240 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002241 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002242 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002243 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002244 return true;
2245 return false;
2246}
2247
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002248/// MergeFunctionDecl - We just parsed a function 'New' from
2249/// declarator D which has the same name and scope as a previous
2250/// declaration 'Old'. Figure out how to resolve this situation,
2251/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002252///
2253/// In C++, New and Old must be declarations that are not
2254/// overloaded. Use IsOverload to determine whether New and Old are
2255/// overloaded, and to select the Old declaration that New should be
2256/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002257///
2258/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002259bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2260 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002261 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002262 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002263 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002264 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002265 if (New->getFriendObjectKind()) {
2266 Diag(New->getLocation(), diag::err_using_decl_friend);
2267 Diag(Shadow->getTargetDecl()->getLocation(),
2268 diag::note_using_decl_target);
2269 Diag(Shadow->getUsingDecl()->getLocation(),
2270 diag::note_using_decl) << 0;
2271 return true;
2272 }
2273
Richard Smith18819302014-02-06 01:31:33 +00002274 // C++11 [namespace.udecl]p14:
2275 // If a function declaration in namespace scope or block scope has the
2276 // same name and the same parameter-type-list as a function introduced
2277 // by a using-declaration, and the declarations do not declare the same
2278 // function, the program is ill-formed.
2279
2280 // Check whether the two declarations might declare the same function.
2281 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2282 if (Old &&
2283 !Old->getDeclContext()->getRedeclContext()->Equals(
2284 New->getDeclContext()->getRedeclContext()) &&
2285 !(Old->isExternC() && New->isExternC()))
2286 Old = 0;
2287
2288 if (!Old) {
2289 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2290 Diag(Shadow->getTargetDecl()->getLocation(),
2291 diag::note_using_decl_target);
2292 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2293 return true;
2294 }
2295 OldD = Old;
2296 } else {
2297 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2298 << New->getDeclName();
2299 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002300 return true;
2301 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002302 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002303
David Majnemerea5092a2013-07-07 23:49:50 +00002304 // If the old declaration is invalid, just give up here.
2305 if (Old->isInvalidDecl())
2306 return true;
2307
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002308 // Determine whether the previous declaration was a definition,
2309 // implicit declaration, or a declaration.
2310 diag::kind PrevDiag;
Richard Smithbdd14642014-02-04 01:14:30 +00002311 SourceLocation OldLocation = Old->getLocation();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002312 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002313 PrevDiag = diag::note_previous_definition;
Richard Smithbdd14642014-02-04 01:14:30 +00002314 else if (Old->isImplicit()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002315 PrevDiag = diag::note_previous_implicit_declaration;
Richard Smithbdd14642014-02-04 01:14:30 +00002316 if (OldLocation.isInvalid())
2317 OldLocation = New->getLocation();
2318 } else
Chris Lattner0369c572008-11-23 23:12:31 +00002319 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002320
Charles Davisfea48452010-02-18 02:00:42 +00002321 // Don't complain about this if we're in GNU89 mode and the old function
2322 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002323 // Don't complain about specializations. They are not supposed to have
2324 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002325 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002326 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002327 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002328 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002329 !canRedefineFunction(Old, getLangOpts())) {
2330 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002331 Diag(New->getLocation(), diag::warn_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002332 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002333 } else {
2334 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002335 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002336 return true;
2337 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002338 }
2339
Reid Kleckner78af0702013-08-27 23:08:25 +00002340
2341 // If a function is first declared with a calling convention, but is later
2342 // declared or defined without one, all following decls assume the calling
2343 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002344 //
John McCalla5f46fb2012-08-25 02:00:03 +00002345 // It's OK if a function is first declared without a calling convention,
2346 // but is later declared or defined with the default calling convention.
2347 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002348 // To test if either decl has an explicit calling convention, we look for
2349 // AttributedType sugar nodes on the type as written. If they are missing or
2350 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002351 //
2352 // Note also that we DO NOT return at this point, because we still have
2353 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002354 QualType OldQType = Context.getCanonicalType(Old->getType());
2355 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002356 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002357 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002358 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2359 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2360 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002361
Reid Kleckner78af0702013-08-27 23:08:25 +00002362 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002363 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002364 const FunctionType *FT =
2365 First->getType().getCanonicalType()->castAs<FunctionType>();
2366 FunctionType::ExtInfo FI = FT->getExtInfo();
2367 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2368 if (!NewCCExplicit) {
2369 // Inherit the CC from the previous declaration if it was specified
2370 // there but not here.
2371 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2372 RequiresAdjustment = true;
2373 } else {
2374 // Calling conventions aren't compatible, so complain.
2375 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2376 Diag(New->getLocation(), diag::err_cconv_change)
2377 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2378 << !FirstCCExplicit
2379 << (!FirstCCExplicit ? "" :
2380 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002381
Reid Kleckner78af0702013-08-27 23:08:25 +00002382 // Put the note on the first decl, since it is the one that matters.
2383 Diag(First->getLocation(), diag::note_previous_declaration);
2384 return true;
2385 }
John McCallcddbad02010-02-04 05:44:44 +00002386 }
2387
John McCallab26cfa2010-02-05 21:31:56 +00002388 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002389 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2390 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2391 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002392 }
2393
Douglas Gregor77e274f2010-06-18 21:30:25 +00002394 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002395 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2396 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2397 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002398 Diag(New->getLocation(), diag::err_regparm_mismatch)
2399 << NewType->getRegParmType()
2400 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002401 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002402 return true;
2403 }
John McCall4f5019e2010-12-19 02:44:49 +00002404
2405 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2406 RequiresAdjustment = true;
2407 }
2408
Douglas Gregorf1404d72011-10-14 15:55:40 +00002409 // Merge ns_returns_retained attribute.
2410 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2411 if (NewTypeInfo.getProducesResult()) {
2412 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002413 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002414 return true;
2415 }
2416
2417 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2418 RequiresAdjustment = true;
2419 }
2420
John McCall4f5019e2010-12-19 02:44:49 +00002421 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002422 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2423 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2424 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002425 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002426 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002427 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002428
2429 // If this redeclaration makes the function inline, we may need to add it to
2430 // UndefinedButUsed.
2431 if (!Old->isInlined() && New->isInlined() &&
2432 !New->hasAttr<GNUInlineAttr>() &&
2433 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2434 Old->isUsed(false) &&
2435 !Old->isDefined() && !New->isThisDeclarationADefinition())
2436 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2437 SourceLocation()));
2438
2439 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2440 // about it.
2441 if (New->hasAttr<GNUInlineAttr>() &&
2442 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2443 UndefinedButUsed.erase(Old->getCanonicalDecl());
2444 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002445
David Blaikiebbafb8a2012-03-11 07:00:24 +00002446 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002447 // (C++98 13.1p2):
2448 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002449 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002450 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002451
2452 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002453 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002454 // Redeclarations or specializations of a function or function template
2455 // with a declared return type that uses a placeholder type shall also
2456 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002457 QualType OldDeclaredReturnType =
2458 (Old->getTypeSourceInfo()
2459 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2460 : OldType)->getReturnType();
2461 QualType NewDeclaredReturnType =
2462 (New->getTypeSourceInfo()
2463 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2464 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002465 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002466 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2467 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2468 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002469 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2470 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002471 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2472 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002473 if (New->isCXXClassMember() && New->isOutOfLine())
2474 Diag(New->getLocation(),
2475 diag::err_member_def_does_not_match_ret_type) << New;
2476 else
2477 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Richard Smithbdd14642014-02-04 01:14:30 +00002478 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002479 return true;
2480 }
2481 else
2482 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002483 }
2484
Alp Toker314cc812014-01-25 16:55:45 +00002485 QualType OldReturnType = OldType->getReturnType();
2486 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002487 if (OldReturnType != NewReturnType) {
2488 // If this function has a deduced return type and has already been
2489 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002490 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002491 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002492 New->setType(
2493 SubstAutoType(New->getType(),
2494 OldAT->isDependentType() ? Context.DependentTy
2495 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002496 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002497 SubstAutoType(NewQType,
2498 OldAT->isDependentType() ? Context.DependentTy
2499 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002500 }
2501 }
2502
2503 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2504 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002505 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002506 // Preserve triviality.
2507 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002508
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002509 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002510 // 2 CXXMethodDecls referring to the same function will be injected.
2511 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002512 bool IsClassScopeExplicitSpecialization =
2513 OldMethod->isFunctionTemplateSpecialization() &&
2514 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002515 bool isFriend = NewMethod->getFriendObjectKind();
2516
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002517 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2518 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002519 // -- Member function declarations with the same name and the
2520 // same parameter types cannot be overloaded if any of them
2521 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002522 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002523 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002524 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002525 return true;
2526 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002527
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002528 // C++ [class.mem]p1:
2529 // [...] A member shall not be declared twice in the
2530 // member-specification, except that a nested class or member
2531 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002532 if (ActiveTemplateInstantiations.empty()) {
2533 unsigned NewDiag;
2534 if (isa<CXXConstructorDecl>(OldMethod))
2535 NewDiag = diag::err_constructor_redeclared;
2536 else if (isa<CXXDestructorDecl>(NewMethod))
2537 NewDiag = diag::err_destructor_redeclared;
2538 else if (isa<CXXConversionDecl>(NewMethod))
2539 NewDiag = diag::err_conv_function_redeclared;
2540 else
2541 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002542
Richard Smith57e7ff92012-07-13 04:12:04 +00002543 Diag(New->getLocation(), NewDiag);
2544 } else {
2545 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2546 << New << New->getType();
2547 }
Richard Smithbdd14642014-02-04 01:14:30 +00002548 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002549
2550 // Complain if this is an explicit declaration of a special
2551 // member that was initially declared implicitly.
2552 //
2553 // As an exception, it's okay to befriend such methods in order
2554 // to permit the implicit constructor/destructor/operator calls.
2555 } else if (OldMethod->isImplicit()) {
2556 if (isFriend) {
2557 NewMethod->setImplicit();
2558 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002559 Diag(NewMethod->getLocation(),
2560 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002561 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002562 return true;
2563 }
Richard Smith337a5a12012-06-08 01:30:54 +00002564 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002565 Diag(NewMethod->getLocation(),
2566 diag::err_definition_of_explicitly_defaulted_member)
2567 << getSpecialMember(OldMethod);
2568 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002569 }
2570 }
2571
Richard Smith10876ef2013-01-17 01:30:42 +00002572 // C++11 [dcl.attr.noreturn]p1:
2573 // The first declaration of a function shall specify the noreturn
2574 // attribute if any declaration of that function specifies the noreturn
2575 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002576 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2577 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2578 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002579 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002580 diag::note_noreturn_missing_first_decl);
2581 }
2582
Richard Smithe233fbf2013-01-28 22:42:45 +00002583 // C++11 [dcl.attr.depend]p2:
2584 // The first declaration of a function shall specify the
2585 // carries_dependency attribute for its declarator-id if any declaration
2586 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002587 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2588 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2589 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002590 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002591 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002592 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2593 }
2594
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002595 // (C++98 8.3.5p3):
2596 // All declarations for a function shall agree exactly in both the
2597 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002598 // We also want to respect all the extended bits except noreturn.
2599
2600 // noreturn should now match unless the old type info didn't have it.
2601 QualType OldQTypeForComparison = OldQType;
2602 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2603 assert(OldQType == QualType(OldType, 0));
2604 const FunctionType *OldTypeForComparison
2605 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2606 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2607 assert(OldQTypeForComparison.isCanonical());
2608 }
2609
Rafael Espindolaf4187652013-02-14 01:18:37 +00002610 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002611 // As a special case, retain the language linkage from previous
2612 // declarations of a friend function as an extension.
2613 //
2614 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2615 // and is useful because there's otherwise no way to specify language
2616 // linkage within class scope.
2617 //
2618 // Check cautiously as the friend object kind isn't yet complete.
2619 if (New->getFriendObjectKind() != Decl::FOK_None) {
2620 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002621 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002622 } else {
2623 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002624 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002625 return true;
2626 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002627 }
2628
John McCall4f5019e2010-12-19 02:44:49 +00002629 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002630 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002631
Richard Smith541b38b2013-09-20 01:15:31 +00002632 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2633 New->isLocalExternDecl()) {
2634 // It's OK if we couldn't merge types for a local function declaraton
2635 // if either the old or new type is dependent. We'll merge the types
2636 // when we instantiate the function.
2637 return false;
2638 }
2639
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002640 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002641 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002642
2643 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002644 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002645 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002646 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002647 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2648 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002649 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002650 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002651 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002652 // The old declaration provided a function prototype, but the
2653 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002654 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002655 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
Alp Toker314cc812014-01-25 16:55:45 +00002656 NewQType =
2657 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2658 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002659 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002660 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002661
Alp Toker4284c6e2014-05-11 16:05:55 +00002662 // Synthesize parameters with the same types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002663 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002664 for (const auto &ParamType : OldProto->param_types()) {
2665 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2666 SourceLocation(), 0, ParamType,
2667 /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002668 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002669 Param->setImplicit();
2670 Params.push_back(Param);
2671 }
2672
David Blaikie9c70e042011-09-21 18:16:56 +00002673 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002674 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002675
Richard Smith1c34fb72013-08-13 18:18:50 +00002676 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002677 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002678
Douglas Gregora74a2972009-03-06 22:43:54 +00002679 // GNU C permits a K&R definition to follow a prototype declaration
2680 // if the declared types of the parameters in the K&R definition
2681 // match the types in the prototype declaration, even when the
2682 // promoted types of the parameters from the K&R definition differ
2683 // from the types in the prototype. GCC then keeps the types from
2684 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002685 //
2686 // If a variadic prototype is followed by a non-variadic K&R definition,
2687 // the K&R definition becomes variadic. This is sort of an edge case, but
2688 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2689 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002690 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002691 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002692 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002693 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002694 SmallVector<QualType, 16> ArgTypes;
2695 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002696 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002697 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002698 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002699 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002700
Douglas Gregora74a2972009-03-06 22:43:54 +00002701 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002702 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2703 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002704 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002705 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002706 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002707 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2708 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002709 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002710 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002711 ArgTypes.push_back(NewParm->getType());
2712 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002713 NewParm->getType(),
2714 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002715 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2716 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002717 Warnings.push_back(Warn);
2718 ArgTypes.push_back(NewParm->getType());
2719 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002720 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002721 }
2722
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002723 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002724 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2725 Diag(Warnings[Warn].NewParm->getLocation(),
2726 diag::ext_param_promoted_not_compatible_with_prototype)
2727 << Warnings[Warn].PromotedType
2728 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002729 if (Warnings[Warn].OldParm->getLocation().isValid())
2730 Diag(Warnings[Warn].OldParm->getLocation(),
2731 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002732 }
2733
Richard Smith1c34fb72013-08-13 18:18:50 +00002734 if (MergeTypeWithOld)
2735 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2736 OldProto->getExtProtoInfo()));
2737 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002738 }
2739
2740 // Fall through to diagnose conflicting types.
2741 }
2742
John McCallad327cd2013-04-14 08:50:55 +00002743 // A function that has already been declared has been redeclared or
2744 // defined with a different type; show an appropriate diagnostic.
2745
2746 // If the previous declaration was an implicitly-generated builtin
2747 // declaration, then at the very least we should use a specialized note.
2748 unsigned BuiltinID;
2749 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2750 // If it's actually a library-defined builtin function like 'malloc'
2751 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002752 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002753 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002754 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002755 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002756
2757 // If this is a global redeclaration, just forget hereafter
2758 // about the "builtin-ness" of the function.
2759 //
2760 // Doing this for local extern declarations is problematic. If
2761 // the builtin declaration remains visible, a second invalid
2762 // local declaration will produce a hard error; if it doesn't
2763 // remain visible, a single bogus local redeclaration (which is
2764 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002765 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002766 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2767
Douglas Gregor893c2c92009-03-23 17:47:24 +00002768 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002769 }
Steve Naroff17832a42008-01-16 15:01:34 +00002770
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002771 PrevDiag = diag::note_previous_builtin_declaration;
2772 }
2773
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002774 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002775 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002776 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002777}
2778
Douglas Gregore62c0a42009-02-24 01:23:02 +00002779/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002780/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002781///
2782/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002783/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002784/// the new declaration, once we know that New is in fact a
2785/// redeclaration of Old.
2786///
2787/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002788bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002789 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002790 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002791 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002792
Douglas Gregore62c0a42009-02-24 01:23:02 +00002793 // Merge "pure" flag.
2794 if (Old->isPure())
2795 New->setPure();
2796
Rafael Espindolabefe1302012-11-25 14:07:59 +00002797 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002798 if (Old->getMostRecentDecl()->isUsed(false))
2799 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002800
John McCallf79e87d2011-03-02 04:00:57 +00002801 // Merge attributes from the parameters. These can mismatch with K&R
2802 // declarations.
2803 if (New->getNumParams() == Old->getNumParams())
2804 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2805 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002806 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002807
David Blaikiebbafb8a2012-03-11 07:00:24 +00002808 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002809 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002810
Rafael Espindola8778c282012-11-29 16:09:03 +00002811 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002812 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2813 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002814 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002815 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002816 New->setType(Merged);
2817
Douglas Gregore62c0a42009-02-24 01:23:02 +00002818 return false;
2819}
2820
John McCall31168b02011-06-15 23:02:42 +00002821
John McCallf79e87d2011-03-02 04:00:57 +00002822void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002823 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002824
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002825 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002826 AvailabilityMergeKind MergeKind =
2827 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2828 : AMK_Override;
2829 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002830
2831 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002832 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2833 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002834 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002835 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002836 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002837 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002838
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002839 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002840}
2841
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002842/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2843/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002844/// emitting diagnostics as appropriate.
2845///
2846/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002847/// to here in AddInitializerToDecl. We can't check them before the initializer
2848/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002849void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2850 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002851 if (New->isInvalidDecl() || Old->isInvalidDecl())
2852 return;
2853
2854 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002855 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002856 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002857 // We don't know what the new type is until the initializer is attached.
2858 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002859 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2860 // These could still be something that needs exception specs checked.
2861 return MergeVarDeclExceptionSpecs(New, Old);
2862 }
Richard Smith30482bc2011-02-20 03:19:35 +00002863 // C++ [basic.link]p10:
2864 // [...] the types specified by all declarations referring to a given
2865 // object or function shall be identical, except that declarations for an
2866 // array object can specify array types that differ by the presence or
2867 // absence of a major array bound (8.3.4).
2868 else if (Old->getType()->isIncompleteArrayType() &&
2869 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002870 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2871 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2872 if (Context.hasSameType(OldArray->getElementType(),
2873 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002874 MergedT = New->getType();
2875 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002876 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002877 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2878 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2879 if (Context.hasSameType(OldArray->getElementType(),
2880 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002881 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002882 } else if (New->getType()->isObjCObjectPointerType() &&
2883 Old->getType()->isObjCObjectPointerType()) {
2884 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2885 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002886 }
2887 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002888 // C 6.2.7p2:
2889 // All declarations that refer to the same object or function shall have
2890 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002891 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2892 }
2893 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002894 // It's OK if we couldn't merge types if either type is dependent, for a
2895 // block-scope variable. In other cases (static data members of class
2896 // templates, variable templates, ...), we require the types to be
2897 // equivalent.
2898 // FIXME: The C++ standard doesn't say anything about this.
2899 if ((New->getType()->isDependentType() ||
2900 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2901 // If the old type was dependent, we can't merge with it, so the new type
2902 // becomes dependent for now. We'll reproduce the original type when we
2903 // instantiate the TypeSourceInfo for the variable.
2904 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2905 New->setType(Context.DependentTy);
2906 return;
2907 }
2908
2909 // FIXME: Even if this merging succeeds, some other non-visible declaration
2910 // of this variable might have an incompatible type. For instance:
2911 //
2912 // extern int arr[];
2913 // void f() { extern int arr[2]; }
2914 // void g() { extern int arr[3]; }
2915 //
2916 // Neither C nor C++ requires a diagnostic for this, but we should still try
2917 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002918 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002919 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002920 Diag(Old->getLocation(), diag::note_previous_definition);
2921 return New->setInvalidDecl();
2922 }
John McCallb65e8fe2013-04-01 18:34:28 +00002923
2924 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002925 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002926 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002927 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002928}
2929
Richard Smith3c785782013-09-03 21:00:58 +00002930static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2931 LookupResult &Previous) {
2932 // C11 6.2.7p4:
2933 // For an identifier with internal or external linkage declared
2934 // in a scope in which a prior declaration of that identifier is
2935 // visible, if the prior declaration specifies internal or
2936 // external linkage, the type of the identifier at the later
2937 // declaration becomes the composite type.
2938 //
2939 // If the variable isn't visible, we do not merge with its type.
2940 if (Previous.isShadowed())
2941 return false;
2942
2943 if (S.getLangOpts().CPlusPlus) {
2944 // C++11 [dcl.array]p3:
2945 // If there is a preceding declaration of the entity in the same
2946 // scope in which the bound was specified, an omitted array bound
2947 // is taken to be the same as in that earlier declaration.
2948 return NewVD->isPreviousDeclInSameBlockScope() ||
2949 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2950 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2951 } else {
2952 // If the old declaration was function-local, don't merge with its
2953 // type unless we're in the same function.
2954 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2955 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2956 }
2957}
2958
Chris Lattner01564d92007-01-27 19:27:06 +00002959/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2960/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2961/// situation, merging decls or emitting diagnostics as appropriate.
2962///
Mike Stump11289f42009-09-09 15:08:12 +00002963/// Tentative definition rules (C99 6.9.2p2) are checked by
2964/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002965/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002966///
Richard Smith3c785782013-09-03 21:00:58 +00002967void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002968 // If the new decl is already invalid, don't do any other checking.
2969 if (New->isInvalidDecl())
2970 return;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Richard Smithbeef3452014-01-16 23:39:20 +00002972 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2973
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002974 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002975 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002976 VarTemplateDecl *OldTemplate = 0;
2977 if (Previous.isSingleResult()) {
2978 if (NewTemplate) {
2979 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2980 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2981 } else
2982 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002983 }
2984 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002985 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002986 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002987 Diag(Previous.getRepresentativeDecl()->getLocation(),
2988 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002989 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002990 }
Chris Lattner84966392008-03-03 03:28:21 +00002991
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00002992 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2993 return;
2994
Richard Smithbeef3452014-01-16 23:39:20 +00002995 // Ensure the template parameters are compatible.
2996 if (NewTemplate &&
2997 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
2998 OldTemplate->getTemplateParameters(),
2999 /*Complain=*/true, TPL_TemplateMatch))
3000 return;
3001
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003002 // C++ [class.mem]p1:
3003 // A member shall not be declared twice in the member-specification [...]
3004 //
3005 // Here, we need only consider static data members.
3006 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3007 Diag(New->getLocation(), diag::err_duplicate_member)
3008 << New->getIdentifier();
3009 Diag(Old->getLocation(), diag::note_previous_declaration);
3010 New->setInvalidDecl();
3011 }
3012
Douglas Gregor32c17572012-01-01 20:30:41 +00003013 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003014 // Warn if an already-declared variable is made a weak_import in a subsequent
3015 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003016 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003017 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003018 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003019 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3020 Diag(Old->getLocation(), diag::note_previous_definition);
3021 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003022 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003023 }
Chris Lattner84966392008-03-03 03:28:21 +00003024
Richard Smith30482bc2011-02-20 03:19:35 +00003025 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003026 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3027
Richard Smith30482bc2011-02-20 03:19:35 +00003028 if (New->isInvalidDecl())
3029 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003030
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003031 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003032 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003033 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003034 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003035 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003036 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003037 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003038 }
Mike Stump11289f42009-09-09 15:08:12 +00003039 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003040 // For an identifier declared with the storage-class specifier
3041 // extern in a scope in which a prior declaration of that
3042 // identifier is visible,23) if the prior declaration specifies
3043 // internal or external linkage, the linkage of the identifier at
3044 // the later declaration is the same as the linkage specified at
3045 // the prior declaration. If no prior declaration is visible, or
3046 // if the prior declaration specifies no linkage, then the
3047 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003048 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003049 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003050 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003051 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003052 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003053 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003054 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003055 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003056 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003057
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003058 // Check if extern is followed by non-extern and vice-versa.
3059 if (New->hasExternalStorage() &&
3060 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3061 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3062 Diag(Old->getLocation(), diag::note_previous_definition);
3063 return New->setInvalidDecl();
3064 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003065 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3066 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003067 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3068 Diag(Old->getLocation(), diag::note_previous_definition);
3069 return New->setInvalidDecl();
3070 }
3071
Steve Naroffa5629372008-09-17 14:05:40 +00003072 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003073
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003074 // FIXME: The test for external storage here seems wrong? We still
3075 // need to check for mismatches.
3076 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003077 // Don't complain about out-of-line definitions of static members.
3078 !(Old->getLexicalDeclContext()->isRecord() &&
3079 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003080 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003081 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003082 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003083 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003084
Richard Smithfd3834f2013-04-13 02:43:54 +00003085 if (New->getTLSKind() != Old->getTLSKind()) {
3086 if (!Old->getTLSKind()) {
3087 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3088 Diag(Old->getLocation(), diag::note_previous_declaration);
3089 } else if (!New->getTLSKind()) {
3090 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3091 Diag(Old->getLocation(), diag::note_previous_declaration);
3092 } else {
3093 // Do not allow redeclaration to change the variable between requiring
3094 // static and dynamic initialization.
3095 // FIXME: GCC allows this, but uses the TLS keyword on the first
3096 // declaration to determine the kind. Do we need to be compatible here?
3097 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3098 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3099 Diag(Old->getLocation(), diag::note_previous_declaration);
3100 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003101 }
3102
Sebastian Redlf1842912010-02-02 18:35:11 +00003103 // C++ doesn't have tentative definitions, so go right ahead and check here.
3104 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003105 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003106 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003107 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003108 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003109 Diag(Def->getLocation(), diag::note_previous_definition);
3110 New->setInvalidDecl();
3111 return;
3112 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003113
Rafael Espindolaf4187652013-02-14 01:18:37 +00003114 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003115 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3116 Diag(Old->getLocation(), diag::note_previous_definition);
3117 New->setInvalidDecl();
3118 return;
3119 }
3120
Rafael Espindolabefe1302012-11-25 14:07:59 +00003121 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003122 if (Old->getMostRecentDecl()->isUsed(false))
3123 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003124
Douglas Gregor0760fa12009-03-10 23:43:53 +00003125 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003126 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003127 if (NewTemplate)
3128 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003129
3130 // Inherit access appropriately.
3131 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003132 if (NewTemplate)
3133 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003134}
3135
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003136/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3137/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003138Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003139 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003140 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003141}
3142
David Majnemer2206bf52014-03-05 08:57:59 +00003143static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003144 if (!S.Context.getLangOpts().CPlusPlus)
3145 return;
3146
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003147 if (isa<CXXRecordDecl>(Tag->getParent())) {
3148 // If this tag is the direct child of a class, number it if
3149 // it is anonymous.
3150 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3151 return;
3152 MangleNumberingContext &MCtx =
3153 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003154 S.Context.setManglingNumber(
3155 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003156 return;
3157 }
3158
3159 // If this tag isn't a direct child of a class, number it if it is local.
3160 Decl *ManglingContextDecl;
3161 if (MangleNumberingContext *MCtx =
3162 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3163 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003164 S.Context.setManglingNumber(
3165 Tag,
3166 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003167 }
3168}
3169
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003170/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003171/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003172/// parameters to cope with template friend declarations.
3173Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3174 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003175 MultiTemplateParamsArg TemplateParams,
3176 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003177 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003178 TagDecl *Tag = 0;
3179 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3180 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003181 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003182 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003183 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003184 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003185
3186 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003187 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003188
John McCall07e91c02009-08-06 02:15:43 +00003189 // Note that the above type specs guarantee that the
3190 // type rep is a Decl, whereas in many of the others
3191 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003192 if (isa<TagDecl>(TagD))
3193 Tag = cast<TagDecl>(TagD);
3194 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3195 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003196 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003197
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003198 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003199 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003200 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003201 if (Tag->isInvalidDecl())
3202 return Tag;
3203 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003204
Nuno Lopese9823fa2009-12-17 11:35:26 +00003205 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3206 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3207 // or incomplete types shall not be restrict-qualified."
3208 if (TypeQuals & DeclSpec::TQ_restrict)
3209 Diag(DS.getRestrictSpecLoc(),
3210 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3211 << DS.getSourceRange();
3212 }
3213
Richard Smitha77a0a62011-08-15 21:04:07 +00003214 if (DS.isConstexprSpecified()) {
3215 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3216 // and definitions of functions and variables.
3217 if (Tag)
3218 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3219 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3220 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003221 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3222 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003223 else
3224 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3225 // Don't emit warnings after this error.
3226 return TagD;
3227 }
3228
Richard Smithb1402ae2013-03-18 22:52:47 +00003229 DiagnoseFunctionSpecifiers(DS);
3230
Douglas Gregor3dad8422009-09-26 06:47:28 +00003231 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003232 // If we're dealing with a decl but not a TagDecl, assume that
3233 // whatever routines created it handled the friendship aspect.
3234 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003235 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003236 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003237 }
John McCallaa017372011-03-22 23:00:04 +00003238
Richard Smithb1402ae2013-03-18 22:52:47 +00003239 CXXScopeSpec &SS = DS.getTypeSpecScope();
3240 bool IsExplicitSpecialization =
3241 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3242 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3243 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3244 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3245 // nested-name-specifier unless it is an explicit instantiation
3246 // or an explicit specialization.
3247 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3248 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3249 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3250 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3251 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3252 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3253 << SS.getRange();
3254 return 0;
3255 }
3256
3257 // Track whether this decl-specifier declares anything.
3258 bool DeclaresAnything = true;
3259
3260 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003261 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003262 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003263 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003264 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003265 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003266 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003267
Richard Smithb1402ae2013-03-18 22:52:47 +00003268 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003269 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003270 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003271
Richard Smithb1402ae2013-03-18 22:52:47 +00003272 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003273 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003274 CurContext->isRecord() &&
3275 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3276 // Handle 2 kinds of anonymous struct:
3277 // struct STRUCT;
3278 // and
3279 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3280 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003281 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003282 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3283 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003284 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003285 << DS.getSourceRange();
3286 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3287 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003288 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003289
3290 // Skip all the checks below if we have a type error.
3291 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3292 (TagD && TagD->isInvalidDecl()))
3293 return TagD;
3294
3295 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003296 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3297 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3298 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003299 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3300 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003301
John McCallaa017372011-03-22 23:00:04 +00003302 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003303 // Customize diagnostic for a typedef missing a name.
3304 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003305 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003306 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003307 else
3308 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003309 }
Mike Stump11289f42009-09-09 15:08:12 +00003310
Richard Smithb1402ae2013-03-18 22:52:47 +00003311 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003312 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3313 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3314 << Tag->getTagKind()
3315 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3316
Richard Smithb1402ae2013-03-18 22:52:47 +00003317 ActOnDocumentableDecl(TagD);
3318
3319 // C 6.7/2:
3320 // A declaration [...] shall declare at least a declarator [...], a tag,
3321 // or the members of an enumeration.
3322 // C++ [dcl.dcl]p3:
3323 // [If there are no declarators], and except for the declaration of an
3324 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3325 // names into the program, or shall redeclare a name introduced by a
3326 // previous declaration.
3327 if (!DeclaresAnything) {
3328 // In C, we allow this as a (popular) extension / bug. Don't bother
3329 // producing further diagnostics for redundant qualifiers after this.
3330 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3331 return TagD;
3332 }
3333
3334 // C++ [dcl.stc]p1:
3335 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3336 // init-declarator-list of the declaration shall not be empty.
3337 // C++ [dcl.fct.spec]p1:
3338 // If a cv-qualifier appears in a decl-specifier-seq, the
3339 // init-declarator-list of the declaration shall not be empty.
3340 //
3341 // Spurious qualifiers here appear to be valid in C.
3342 unsigned DiagID = diag::warn_standalone_specifier;
3343 if (getLangOpts().CPlusPlus)
3344 DiagID = diag::ext_standalone_specifier;
3345
3346 // Note that a linkage-specification sets a storage class, but
3347 // 'extern "C" struct foo;' is actually valid and not theoretically
3348 // useless.
3349 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3350 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3351 Diag(DS.getStorageClassSpecLoc(), DiagID)
3352 << DeclSpec::getSpecifierName(SCS);
3353
Richard Smithb4a9e862013-04-12 22:46:28 +00003354 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3355 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3356 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003357 if (DS.getTypeQualifiers()) {
3358 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3359 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3360 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3361 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3362 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003363 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3364 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003365 }
3366
Eli Friedmane3217952011-12-17 00:36:09 +00003367 // Warn about ignored type attributes, for example:
3368 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003369 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003370 if (!DS.getAttributes().empty()) {
3371 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3372 if (TypeSpecType == DeclSpec::TST_class ||
3373 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003374 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003375 TypeSpecType == DeclSpec::TST_union ||
3376 TypeSpecType == DeclSpec::TST_enum) {
3377 AttributeList* attrs = DS.getAttributes().getList();
3378 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003379 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003380 << attrs->getName()
3381 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3382 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003383 TypeSpecType == DeclSpec::TST_union ? 2 :
3384 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003385 attrs = attrs->getNext();
3386 }
3387 }
3388 }
John McCallaa017372011-03-22 23:00:04 +00003389
John McCall48871652010-08-21 09:40:31 +00003390 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003391}
3392
John McCallea305ed2009-12-18 10:40:03 +00003393/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003394/// check if there's an existing declaration that can't be overloaded.
3395///
3396/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003397static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3398 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003399 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003400 DeclarationName Name,
3401 SourceLocation NameLoc,
3402 unsigned diagnostic) {
3403 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3404 Sema::ForRedeclaration);
3405 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003406
John McCallea305ed2009-12-18 10:40:03 +00003407 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003408 return false;
3409
3410 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003411 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003412 assert(PrevDecl && "Expected a non-null Decl");
3413
3414 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3415 return false;
John McCall1f82f242009-11-18 22:49:29 +00003416
John McCallea305ed2009-12-18 10:40:03 +00003417 SemaRef.Diag(NameLoc, diagnostic) << Name;
3418 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003419
3420 return true;
3421}
3422
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003423/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3424/// anonymous struct or union AnonRecord into the owning context Owner
3425/// and scope S. This routine will be invoked just after we realize
3426/// that an unnamed union or struct is actually an anonymous union or
3427/// struct, e.g.,
3428///
3429/// @code
3430/// union {
3431/// int i;
3432/// float f;
3433/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3434/// // f into the surrounding scope.x
3435/// @endcode
3436///
3437/// This routine is recursive, injecting the names of nested anonymous
3438/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003439static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003440 DeclContext *Owner,
3441 RecordDecl *AnonRecord,
3442 AccessSpecifier AS,
3443 SmallVectorImpl<NamedDecl *> &Chaining,
3444 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003445 unsigned diagKind
3446 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3447 : diag::err_anonymous_struct_member_redecl;
3448
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003449 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003450
3451 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003452 for (auto *D : AnonRecord->decls()) {
3453 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3454 cast<NamedDecl>(D)->getDeclName()) {
3455 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003456 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3457 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003458 // C++ [class.union]p2:
3459 // The names of the members of an anonymous union shall be
3460 // distinct from the names of any other entity in the
3461 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003462 Invalid = true;
3463 } else {
3464 // C++ [class.union]p2:
3465 // For the purpose of name lookup, after the anonymous union
3466 // definition, the members of the anonymous union are
3467 // considered to have been defined in the scope in which the
3468 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003469 unsigned OldChainingSize = Chaining.size();
3470 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003471 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003472 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003473 else
3474 Chaining.push_back(VD);
3475
Francois Pichet783dd6e2010-11-21 06:08:52 +00003476 assert(Chaining.size() >= 2);
3477 NamedDecl **NamedChain =
3478 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3479 for (unsigned i = 0; i < Chaining.size(); i++)
3480 NamedChain[i] = Chaining[i];
3481
3482 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003483 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3484 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003485 NamedChain, Chaining.size());
3486
3487 IndirectField->setAccess(AS);
3488 IndirectField->setImplicit();
3489 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003490
3491 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003492 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003493
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003494 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003495 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003496 }
3497 }
3498
3499 return Invalid;
3500}
3501
Douglas Gregorc4df4072010-04-19 22:54:31 +00003502/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3503/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003504/// illegal input values are mapped to SC_None.
3505static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003506StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3507 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3508 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3509 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003510 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003511 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003512 case DeclSpec::SCS_extern:
3513 if (DS.isExternInLinkageSpec())
3514 return SC_None;
3515 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003516 case DeclSpec::SCS_static: return SC_Static;
3517 case DeclSpec::SCS_auto: return SC_Auto;
3518 case DeclSpec::SCS_register: return SC_Register;
3519 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003520 // Illegal SCSs map to None: error reporting is up to the caller.
3521 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003522 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003523 }
3524 llvm_unreachable("unknown storage class specifier");
3525}
3526
Richard Smithab44d5b2013-12-10 08:25:00 +00003527static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3528 assert(Record->hasInClassInitializer());
3529
Aaron Ballman629afae2014-03-07 19:56:05 +00003530 for (const auto *I : Record->decls()) {
3531 const auto *FD = dyn_cast<FieldDecl>(I);
3532 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003533 FD = IFD->getAnonField();
3534 if (FD && FD->hasInClassInitializer())
3535 return FD->getLocation();
3536 }
3537
3538 llvm_unreachable("couldn't find in-class initializer");
3539}
3540
3541static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3542 SourceLocation DefaultInitLoc) {
3543 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3544 return;
3545
3546 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3547 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3548}
3549
3550static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3551 CXXRecordDecl *AnonUnion) {
3552 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3553 return;
3554
3555 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3556}
3557
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003558/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003559/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003560/// (C++ [class.union]) and a C11 feature; anonymous structures
3561/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003562Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003563 AccessSpecifier AS,
3564 RecordDecl *Record,
3565 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003566 DeclContext *Owner = Record->getDeclContext();
3567
3568 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003569 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003570 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003571 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003572 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003574 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003575
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003576 // C and C++ require different kinds of checks for anonymous
3577 // structs/unions.
3578 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003579 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003580 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003581 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003582 if (Record->isUnion()) {
3583 // C++ [class.union]p6:
3584 // Anonymous unions declared in a named namespace or in the
3585 // global namespace shall be declared static.
3586 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3587 (isa<TranslationUnitDecl>(Owner) ||
3588 (isa<NamespaceDecl>(Owner) &&
3589 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003590 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3591 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003592
3593 // Recover by adding 'static'.
3594 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003595 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003596 }
3597 // C++ [class.union]p6:
3598 // A storage class is not allowed in a declaration of an
3599 // anonymous union in a class scope.
3600 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3601 isa<RecordDecl>(Owner)) {
3602 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003603 diag::err_anonymous_union_with_storage_spec)
3604 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003605
3606 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003607 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3608 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003609 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003610 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003611 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003612
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003613 // Ignore const/volatile/restrict qualifiers.
3614 if (DS.getTypeQualifiers()) {
3615 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3616 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003617 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003618 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3619 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003620 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003621 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003622 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003623 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3624 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003625 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003626 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003627 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003628 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003629 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3630 Diag(DS.getAtomicSpecLoc(),
3631 diag::ext_anonymous_struct_union_qualified)
3632 << Record->isUnion() << "_Atomic"
3633 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003634
3635 DS.ClearTypeQualifiers();
3636 }
3637
Mike Stump11289f42009-09-09 15:08:12 +00003638 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003639 // The member-specification of an anonymous union shall only
3640 // define non-static data members. [Note: nested types and
3641 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003642 for (auto *Mem : Record->decls()) {
3643 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003644 // C++ [class.union]p3:
3645 // An anonymous union shall not have private or protected
3646 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003647 assert(FD->getAccess() != AS_none);
3648 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003649 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3650 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3651 Invalid = true;
3652 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003653
Alexis Hunt97ab5542011-05-16 22:41:40 +00003654 // C++ [class.union]p1
3655 // An object of a class with a non-trivial constructor, a non-trivial
3656 // copy constructor, a non-trivial destructor, or a non-trivial copy
3657 // assignment operator cannot be a member of a union, nor can an
3658 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003659 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003660 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003661 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003662 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003663 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003664 // This is a type that showed up in an
3665 // elaborated-type-specifier inside the anonymous struct or
3666 // union, but which actually declares a type outside of the
3667 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003668 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003669 if (!MemRecord->isAnonymousStructOrUnion() &&
3670 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003671 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003672 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003673 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3674 << (int)Record->isUnion();
3675 else {
3676 // This is a nested type declaration.
3677 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3678 << (int)Record->isUnion();
3679 Invalid = true;
3680 }
Richard Smith254d2662013-01-28 00:54:05 +00003681 } else {
3682 // This is an anonymous type definition within another anonymous type.
3683 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3684 // not part of standard C++.
3685 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003686 diag::ext_anonymous_record_with_anonymous_type)
3687 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003688 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003689 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003690 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003691 } else {
3692 // We have something that isn't a non-static data
3693 // member. Complain about it.
3694 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003695 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003696 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003697 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003698 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003699 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003700 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003701
3702 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003703 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003704 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003705 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003706 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003707 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003708 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003709 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003710 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003711 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003712 }
3713 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003714
3715 // C++11 [class.union]p8 (DR1460):
3716 // At most one variant member of a union may have a
3717 // brace-or-equal-initializer.
3718 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3719 Owner->isRecord())
3720 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3721 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003722 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003723
3724 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003725 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003726 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003727 Invalid = true;
3728 }
3729
John McCallfa2d6922009-10-22 23:31:08 +00003730 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003731 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003732 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003733 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003734
Mike Stump11289f42009-09-09 15:08:12 +00003735 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003736 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003737 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003738 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003739 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003740 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003741 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003742 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003743 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003744 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003745 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003746 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003747 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003748 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003749 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003750 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003751 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003752 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003753 // mutable can only appear on non-static class members, so it's always
3754 // an error here
3755 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3756 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003757 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003758 }
3759
Abramo Bagnaradff19302011-03-08 08:55:46 +00003760 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003761 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003762 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003763 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003764 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003765
3766 // Default-initialize the implicit variable. This initialization will be
3767 // trivial in almost all cases, except if a union member has an in-class
3768 // initializer:
3769 // union { int n = 0; };
3770 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003771 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003772 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003773
Richard Smithab44d5b2013-12-10 08:25:00 +00003774 // Mark this as an anonymous struct/union type.
3775 Record->setAnonymousStructOrUnion(true);
3776
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003777 // Add the anonymous struct/union object to the current
3778 // context. We'll be referencing this object when we refer to one of
3779 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003780 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003781
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003782 // Inject the members of the anonymous struct/union into the owning
3783 // context and into the identifier resolver chain for name lookup
3784 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003785 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003786 Chain.push_back(Anon);
3787
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003788 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3789 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003790 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003791
David Majnemer2206bf52014-03-05 08:57:59 +00003792 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3793 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3794 Decl *ManglingContextDecl;
3795 if (MangleNumberingContext *MCtx =
3796 getCurrentMangleNumberContext(NewVD->getDeclContext(),
3797 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003798 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00003799 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3800 }
3801 }
3802 }
3803
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003804 if (Invalid)
3805 Anon->setInvalidDecl();
3806
John McCall48871652010-08-21 09:40:31 +00003807 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003808}
3809
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003810/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3811/// Microsoft C anonymous structure.
3812/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3813/// Example:
3814///
3815/// struct A { int a; };
3816/// struct B { struct A; int b; };
3817///
3818/// void foo() {
3819/// B var;
3820/// var.a = 3;
3821/// }
3822///
3823Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3824 RecordDecl *Record) {
3825
3826 // If there is no Record, get the record via the typedef.
3827 if (!Record)
3828 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3829
3830 // Mock up a declarator.
3831 Declarator Dc(DS, Declarator::TypeNameContext);
3832 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3833 assert(TInfo && "couldn't build declarator info for anonymous struct");
3834
3835 // Create a declaration for this anonymous struct.
3836 NamedDecl* Anon = FieldDecl::Create(Context,
3837 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003838 DS.getLocStart(),
3839 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003840 /*IdentifierInfo=*/0,
3841 Context.getTypeDeclType(Record),
3842 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003843 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003844 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003845 Anon->setImplicit();
3846
3847 // Add the anonymous struct object to the current context.
3848 CurContext->addDecl(Anon);
3849
3850 // Inject the members of the anonymous struct into the current
3851 // context and into the identifier resolver chain for name lookup
3852 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003853 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003854 Chain.push_back(Anon);
3855
Nico Weberf8bb3de2012-02-01 00:41:00 +00003856 RecordDecl *RecordDef = Record->getDefinition();
3857 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3858 RecordDef, AS_none,
3859 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003860 Anon->setInvalidDecl();
3861
3862 return Anon;
3863}
Steve Naroff2fea1392007-09-02 02:04:30 +00003864
Douglas Gregor92751d42008-11-17 22:58:34 +00003865/// GetNameForDeclarator - Determine the full declaration name for the
3866/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003867DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003868 return GetNameFromUnqualifiedId(D.getName());
3869}
3870
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003871/// \brief Retrieves the declaration name from a parsed unqualified-id.
3872DeclarationNameInfo
3873Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3874 DeclarationNameInfo NameInfo;
3875 NameInfo.setLoc(Name.StartLocation);
3876
Douglas Gregor7861a802009-11-03 01:35:08 +00003877 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003878
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003879 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003880 case UnqualifiedId::IK_Identifier:
3881 NameInfo.setName(Name.Identifier);
3882 NameInfo.setLoc(Name.StartLocation);
3883 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003884
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003885 case UnqualifiedId::IK_OperatorFunctionId:
3886 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3887 Name.OperatorFunctionId.Operator));
3888 NameInfo.setLoc(Name.StartLocation);
3889 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3890 = Name.OperatorFunctionId.SymbolLocations[0];
3891 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3892 = Name.EndLocation.getRawEncoding();
3893 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003894
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003895 case UnqualifiedId::IK_LiteralOperatorId:
3896 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3897 Name.Identifier));
3898 NameInfo.setLoc(Name.StartLocation);
3899 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3900 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003901
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003902 case UnqualifiedId::IK_ConversionFunctionId: {
3903 TypeSourceInfo *TInfo;
3904 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3905 if (Ty.isNull())
3906 return DeclarationNameInfo();
3907 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3908 Context.getCanonicalType(Ty)));
3909 NameInfo.setLoc(Name.StartLocation);
3910 NameInfo.setNamedTypeInfo(TInfo);
3911 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003912 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003913
3914 case UnqualifiedId::IK_ConstructorName: {
3915 TypeSourceInfo *TInfo;
3916 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3917 if (Ty.isNull())
3918 return DeclarationNameInfo();
3919 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3920 Context.getCanonicalType(Ty)));
3921 NameInfo.setLoc(Name.StartLocation);
3922 NameInfo.setNamedTypeInfo(TInfo);
3923 return NameInfo;
3924 }
3925
3926 case UnqualifiedId::IK_ConstructorTemplateId: {
3927 // In well-formed code, we can only have a constructor
3928 // template-id that refers to the current context, so go there
3929 // to find the actual type being constructed.
3930 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3931 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3932 return DeclarationNameInfo();
3933
3934 // Determine the type of the class being constructed.
3935 QualType CurClassType = Context.getTypeDeclType(CurClass);
3936
3937 // FIXME: Check two things: that the template-id names the same type as
3938 // CurClassType, and that the template-id does not occur when the name
3939 // was qualified.
3940
3941 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3942 Context.getCanonicalType(CurClassType)));
3943 NameInfo.setLoc(Name.StartLocation);
3944 // FIXME: should we retrieve TypeSourceInfo?
3945 NameInfo.setNamedTypeInfo(0);
3946 return NameInfo;
3947 }
3948
3949 case UnqualifiedId::IK_DestructorName: {
3950 TypeSourceInfo *TInfo;
3951 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3952 if (Ty.isNull())
3953 return DeclarationNameInfo();
3954 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3955 Context.getCanonicalType(Ty)));
3956 NameInfo.setLoc(Name.StartLocation);
3957 NameInfo.setNamedTypeInfo(TInfo);
3958 return NameInfo;
3959 }
3960
3961 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003962 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003963 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3964 return Context.getNameForTemplate(TName, TNameLoc);
3965 }
3966
3967 } // switch (Name.getKind())
3968
David Blaikie83d382b2011-09-23 05:06:16 +00003969 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003970}
3971
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003972static QualType getCoreType(QualType Ty) {
3973 do {
3974 if (Ty->isPointerType() || Ty->isReferenceType())
3975 Ty = Ty->getPointeeType();
3976 else if (Ty->isArrayType())
3977 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3978 else
3979 return Ty.withoutLocalFastQualifiers();
3980 } while (true);
3981}
3982
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003983/// hasSimilarParameters - Determine whether the C++ functions Declaration
3984/// and Definition have "nearly" matching parameters. This heuristic is
3985/// used to improve diagnostics in the case where an out-of-line function
3986/// definition doesn't match any declaration within the class or namespace.
3987/// Also sets Params to the list of indices to the parameters that differ
3988/// between the declaration and the definition. If hasSimilarParameters
3989/// returns true and Params is empty, then all of the parameters match.
3990static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003991 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003992 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003993 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003994 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003995 if (Declaration->param_size() != Definition->param_size())
3996 return false;
3997 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3998 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3999 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4000
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004001 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004002 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004003 continue;
4004
4005 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4006 QualType DefParamBaseTy = getCoreType(DefParamTy);
4007 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4008 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4009
4010 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4011 (DeclTyName && DeclTyName == DefTyName))
4012 Params.push_back(Idx);
4013 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004014 return false;
4015 }
4016
4017 return true;
4018}
4019
John McCall99b2fe52010-04-29 23:50:39 +00004020/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4021/// declarator needs to be rebuilt in the current instantiation.
4022/// Any bits of declarator which appear before the name are valid for
4023/// consideration here. That's specifically the type in the decl spec
4024/// and the base type in any member-pointer chunks.
4025static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4026 DeclarationName Name) {
4027 // The types we specifically need to rebuild are:
4028 // - typenames, typeofs, and decltypes
4029 // - types which will become injected class names
4030 // Of course, we also need to rebuild any type referencing such a
4031 // type. It's safest to just say "dependent", but we call out a
4032 // few cases here.
4033
4034 DeclSpec &DS = D.getMutableDeclSpec();
4035 switch (DS.getTypeSpecType()) {
4036 case DeclSpec::TST_typename:
4037 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004038 case DeclSpec::TST_underlyingType:
4039 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004040 // Grab the type from the parser.
4041 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004042 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004043 if (T.isNull() || !T->isDependentType()) break;
4044
4045 // Make sure there's a type source info. This isn't really much
4046 // of a waste; most dependent types should have type source info
4047 // attached already.
4048 if (!TSI)
4049 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4050
4051 // Rebuild the type in the current instantiation.
4052 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4053 if (!TSI) return true;
4054
4055 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004056 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4057 DS.UpdateTypeRep(LocType);
4058 break;
4059 }
4060
Richard Smith1620ebd2012-10-01 20:35:07 +00004061 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004062 case DeclSpec::TST_typeofExpr: {
4063 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004064 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004065 if (Result.isInvalid()) return true;
4066 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004067 break;
4068 }
4069
4070 default:
4071 // Nothing to do for these decl specs.
4072 break;
4073 }
4074
4075 // It doesn't matter what order we do this in.
4076 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4077 DeclaratorChunk &Chunk = D.getTypeObject(I);
4078
4079 // The only type information in the declarator which can come
4080 // before the declaration name is the base type of a member
4081 // pointer.
4082 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4083 continue;
4084
4085 // Rebuild the scope specifier in-place.
4086 CXXScopeSpec &SS = Chunk.Mem.Scope();
4087 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4088 return true;
4089 }
4090
4091 return false;
4092}
4093
Anders Carlsson1052fd72011-07-04 16:28:17 +00004094Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004095 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004096 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004097
4098 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004099 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004100 Dcl->setTopLevelDeclInObjCContainer();
4101
4102 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004103}
4104
Richard Smithdda56e42011-04-15 14:24:37 +00004105/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4106/// If T is the name of a class, then each of the following shall have a
4107/// name different from T:
4108/// - every static data member of class T;
4109/// - every member function of class T
4110/// - every member of class T that is itself a type;
4111/// \returns true if the declaration name violates these rules.
4112bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4113 DeclarationNameInfo NameInfo) {
4114 DeclarationName Name = NameInfo.getName();
4115
4116 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4117 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4118 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4119 return true;
4120 }
4121
4122 return false;
4123}
Douglas Gregor31feb332012-03-17 23:06:31 +00004124
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004125/// \brief Diagnose a declaration whose declarator-id has the given
4126/// nested-name-specifier.
4127///
4128/// \param SS The nested-name-specifier of the declarator-id.
4129///
4130/// \param DC The declaration context to which the nested-name-specifier
4131/// resolves.
4132///
4133/// \param Name The name of the entity being declared.
4134///
4135/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004136///
4137/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004138bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004139 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004140 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004141 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004142 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004143 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004144
4145 // If the user provided a superfluous scope specifier that refers back to the
4146 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004147 //
4148 // class X {
4149 // void X::f();
4150 // };
Richard Smitha2302242013-12-05 07:51:02 +00004151 //
4152 // Note, it was once ill-formed to give redundant qualification in all
4153 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004154 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004155 if (Cur->isRecord()) {
4156 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4157 : diag::err_member_extra_qualification)
4158 << Name << FixItHint::CreateRemoval(SS.getRange());
4159 SS.clear();
4160 } else {
4161 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4162 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004163 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004164 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004165
4166 // Check whether the qualifying scope encloses the scope of the original
4167 // declaration.
4168 if (!Cur->Encloses(DC)) {
4169 if (Cur->isRecord())
4170 Diag(Loc, diag::err_member_qualification)
4171 << Name << SS.getRange();
4172 else if (isa<TranslationUnitDecl>(DC))
4173 Diag(Loc, diag::err_invalid_declarator_global_scope)
4174 << Name << SS.getRange();
4175 else if (isa<FunctionDecl>(Cur))
4176 Diag(Loc, diag::err_invalid_declarator_in_function)
4177 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004178 else if (isa<BlockDecl>(Cur))
4179 Diag(Loc, diag::err_invalid_declarator_in_block)
4180 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004181 else
4182 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004183 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004184
Douglas Gregor31feb332012-03-17 23:06:31 +00004185 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004186 }
4187
4188 if (Cur->isRecord()) {
4189 // Cannot qualify members within a class.
4190 Diag(Loc, diag::err_member_qualification)
4191 << Name << SS.getRange();
4192 SS.clear();
4193
4194 // C++ constructors and destructors with incorrect scopes can break
4195 // our AST invariants by having the wrong underlying types. If
4196 // that's the case, then drop this declaration entirely.
4197 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4198 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4199 !Context.hasSameType(Name.getCXXNameType(),
4200 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4201 return true;
4202
4203 return false;
4204 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004205
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004206 // C++11 [dcl.meaning]p1:
4207 // [...] "The nested-name-specifier of the qualified declarator-id shall
4208 // not begin with a decltype-specifer"
4209 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4210 while (SpecLoc.getPrefix())
4211 SpecLoc = SpecLoc.getPrefix();
4212 if (dyn_cast_or_null<DecltypeType>(
4213 SpecLoc.getNestedNameSpecifier()->getAsType()))
4214 Diag(Loc, diag::err_decltype_in_declarator)
4215 << SpecLoc.getTypeLoc().getSourceRange();
4216
Douglas Gregor31feb332012-03-17 23:06:31 +00004217 return false;
4218}
4219
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004220NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4221 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004222 // TODO: consider using NameInfo for diagnostic.
4223 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4224 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004225
Chris Lattner02c04392007-07-25 00:24:17 +00004226 // All of these full declarators require an identifier. If it doesn't have
4227 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004228 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004229 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004230 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004231 diag::err_declarator_need_ident)
4232 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004233 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004234 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4235 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004236
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004237 // The scope passed in may not be a decl scope. Zip up the scope tree until
4238 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004239 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004240 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004241 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004242
John McCall99b2fe52010-04-29 23:50:39 +00004243 DeclContext *DC = CurContext;
4244 if (D.getCXXScopeSpec().isInvalid())
4245 D.setInvalidType();
4246 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004247 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4248 UPPC_DeclarationQualifier))
4249 return 0;
4250
John McCall99b2fe52010-04-29 23:50:39 +00004251 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4252 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004253 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004254 // If we could not compute the declaration context, it's because the
4255 // declaration context is dependent but does not refer to a class,
4256 // class template, or class template partial specialization. Complain
4257 // and return early, to avoid the coming semantic disaster.
4258 Diag(D.getIdentifierLoc(),
4259 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004260 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004261 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004262 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004263 }
John McCall99b2fe52010-04-29 23:50:39 +00004264 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004265
John McCall99b2fe52010-04-29 23:50:39 +00004266 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004267 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004268 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004269
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004270 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4271 Diag(D.getIdentifierLoc(),
4272 diag::err_member_def_undefined_record)
4273 << Name << DC << D.getCXXScopeSpec().getRange();
4274 D.setInvalidType();
4275 } else if (!D.getDeclSpec().isFriendSpecified()) {
4276 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4277 Name, D.getIdentifierLoc())) {
4278 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004279 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004280
4281 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004282 }
John McCall99b2fe52010-04-29 23:50:39 +00004283 }
4284
4285 // Check whether we need to rebuild the type of the given
4286 // declaration in the current instantiation.
4287 if (EnteringContext && IsDependentContext &&
4288 TemplateParamLists.size() != 0) {
4289 ContextRAII SavedContext(*this, DC);
4290 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4291 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004292 }
4293 }
Richard Smithdda56e42011-04-15 14:24:37 +00004294
4295 if (DiagnoseClassNameShadow(DC, NameInfo))
4296 // If this is a typedef, we'll end up spewing multiple diagnostics.
4297 // Just return early; it's safer.
4298 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4299 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004300
John McCall8cb7bdf2010-06-04 23:28:52 +00004301 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4302 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004303
Douglas Gregor506bd562010-12-13 22:49:22 +00004304 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4305 UPPC_DeclarationType))
4306 D.setInvalidType();
4307
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004308 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004309 ForRedeclaration);
4310
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004311 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004312 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004313 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004314 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004315
4316 // If the declaration we're planning to build will be a function
4317 // or object with linkage, then look for another declaration with
4318 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004319 //
4320 // If the declaration we're planning to build will be declared with
4321 // external linkage in the translation unit, create any builtin with
4322 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004323 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4324 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004325 else if (CurContext->isFunctionOrMethod() &&
4326 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4327 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004328 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004329 CreateBuiltins =
4330 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4331 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4332 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4333 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004334
4335 if (IsLinkageLookup)
4336 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004337
Richard Smith1c34fb72013-08-13 18:18:50 +00004338 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004339 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004340 LookupQualifiedName(Previous, DC);
4341
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004342 // C++ [dcl.meaning]p1:
4343 // When the declarator-id is qualified, the declaration shall refer to a
4344 // previously declared member of the class or namespace to which the
4345 // qualifier refers (or, in the case of a namespace, of an element of the
4346 // inline namespace set of that namespace (7.3.1)) or to a specialization
4347 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004348 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004349 // Note that we already checked the context above, and that we do not have
4350 // enough information to make sure that Previous contains the declaration
4351 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004352 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004353 // class X {
4354 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004355 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004356 // };
4357 //
Douglas Gregorad590502008-12-15 23:53:10 +00004358 // void X::f(int) { } // ill-formed
4359 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004360 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004361 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004362 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004363
4364 // C++ [dcl.meaning]p1:
4365 // [...] the member shall not merely have been introduced by a
4366 // using-declaration in the scope of the class or namespace nominated by
4367 // the nested-name-specifier of the declarator-id.
4368 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004369 }
4370
John McCall1f82f242009-11-18 22:49:29 +00004371 if (Previous.isSingleResult() &&
4372 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004373 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004374 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004375 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4376 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004377
Douglas Gregor5101c242008-12-05 18:15:24 +00004378 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004379 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004380 }
4381
Douglas Gregor83a586e2008-04-13 21:07:44 +00004382 // In C++, the previous declaration we find might be a tag type
4383 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004384 // tag type. Note that this does does not apply if we're declaring a
4385 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004386 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004387 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004388 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004389
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004390 // Check that there are no default arguments other than in the parameters
4391 // of a function declaration (C++ only).
4392 if (getLangOpts().CPlusPlus)
4393 CheckExtraCXXDefaultArguments(D);
4394
Nico Webercb4c7f42012-12-23 00:40:46 +00004395 NamedDecl *New;
4396
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004397 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004398 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004399 if (TemplateParamLists.size()) {
4400 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004401 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004402 }
Mike Stump11289f42009-09-09 15:08:12 +00004403
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004404 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004405 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004406 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004407 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004408 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004409 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004410 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4411 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004412 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004413
4414 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004415 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004416
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004417 // If this has an identifier and is not an invalid redeclaration or
4418 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004419 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004420 !(D.isRedeclaration() && New->isInvalidDecl())) {
4421 // Only make a locally-scoped extern declaration visible if it is the first
4422 // declaration of this entity. Qualified lookup for such an entity should
4423 // only find this declaration if there is no visible declaration of it.
4424 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4425 PushOnScopeChains(New, S, AddToContext);
4426 if (!AddToContext)
4427 CurContext->addHiddenDecl(New);
4428 }
Mike Stump11289f42009-09-09 15:08:12 +00004429
John McCall48871652010-08-21 09:40:31 +00004430 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004431}
4432
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004433/// Helper method to turn variable array types into constant array
4434/// types in certain situations which would otherwise be errors (for
4435/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004436static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4437 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004438 bool &SizeIsNegative,
4439 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004440 // This method tries to turn a variable array into a constant
4441 // array even when the size isn't an ICE. This is necessary
4442 // for compatibility with code that depends on gcc's buggy
4443 // constant expression folding, like struct {char x[(int)(char*)2];}
4444 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004445 Oversized = 0;
4446
4447 if (T->isDependentType())
4448 return QualType();
4449
John McCall8ccfcb52009-09-24 19:53:00 +00004450 QualifierCollector Qs;
4451 const Type *Ty = Qs.strip(T);
4452
4453 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004454 QualType Pointee = PTy->getPointeeType();
4455 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004456 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4457 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004458 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004459 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004460 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004461 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004462 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4463 QualType Inner = PTy->getInnerType();
4464 QualType FixedType =
4465 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4466 Oversized);
4467 if (FixedType.isNull()) return FixedType;
4468 FixedType = Context.getParenType(FixedType);
4469 return Qs.apply(Context, FixedType);
4470 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004471
4472 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004473 if (!VLATy)
4474 return QualType();
4475 // FIXME: We should probably handle this case
4476 if (VLATy->getElementType()->isVariablyModifiedType())
4477 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004478
Richard Smith42d3af92011-12-07 00:43:50 +00004479 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004480 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004481 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004482 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004483
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004484 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004485 if (Res.isSigned() && Res.isNegative()) {
4486 SizeIsNegative = true;
4487 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004488 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004489
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004490 // Check whether the array is too large to be addressed.
4491 unsigned ActiveSizeBits
4492 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4493 Res);
4494 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4495 Oversized = Res;
4496 return QualType();
4497 }
4498
4499 return Context.getConstantArrayType(VLATy->getElementType(),
4500 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004501}
4502
Abramo Bagnara341ab732012-11-08 14:44:42 +00004503static void
4504FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004505 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4506 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4507 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4508 DstPTL.getPointeeLoc());
4509 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004510 return;
4511 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004512 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4513 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4514 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4515 DstPTL.getInnerLoc());
4516 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4517 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004518 return;
4519 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004520 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4521 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4522 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4523 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004524 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004525 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4526 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4527 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004528}
4529
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004530/// Helper method to turn variable array types into constant array
4531/// types in certain situations which would otherwise be errors (for
4532/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004533static TypeSourceInfo*
4534TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4535 ASTContext &Context,
4536 bool &SizeIsNegative,
4537 llvm::APSInt &Oversized) {
4538 QualType FixedTy
4539 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4540 SizeIsNegative, Oversized);
4541 if (FixedTy.isNull())
4542 return 0;
4543 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4544 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4545 FixedTInfo->getTypeLoc());
4546 return FixedTInfo;
4547}
4548
Richard Smith78165b52013-01-10 23:43:47 +00004549/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004550/// that it can be found later for redeclarations. We include any extern "C"
4551/// declaration that is not visible in the translation unit here, not just
4552/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004553void
Richard Smith39b79682013-06-18 20:15:12 +00004554Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004555 if (!getLangOpts().CPlusPlus &&
4556 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4557 // Don't need to track declarations in the TU in C.
4558 return;
4559
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004560 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004561 // FIXME: There can be multiple such declarations if they are functions marked
4562 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004563 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004564}
4565
Richard Smith39b79682013-06-18 20:15:12 +00004566NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004567 if (ExternalSource) {
4568 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004569 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004570 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004571 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004572 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4573 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004574 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4575 if (Pos == LocallyScopedExternCDecls.end())
4576 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004577 }
4578 }
Richard Smith39b79682013-06-18 20:15:12 +00004579
4580 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004581 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004582}
4583
Eli Friedman574c7452009-04-07 19:37:57 +00004584/// \brief Diagnose function specifiers on a declaration of an identifier that
4585/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004586void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004587 // FIXME: We should probably indicate the identifier in question to avoid
4588 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004589 if (DS.isInlineSpecified())
4590 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004591 diag::err_inline_non_function);
4592
Richard Smithb1402ae2013-03-18 22:52:47 +00004593 if (DS.isVirtualSpecified())
4594 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004595 diag::err_virtual_non_function);
4596
Richard Smithb1402ae2013-03-18 22:52:47 +00004597 if (DS.isExplicitSpecified())
4598 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004599 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004600
Richard Smithb1402ae2013-03-18 22:52:47 +00004601 if (DS.isNoreturnSpecified())
4602 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004603 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004604}
4605
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004606NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004607Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004608 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004609 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4610 if (D.getCXXScopeSpec().isSet()) {
4611 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4612 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004613 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004614 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004615 DC = CurContext;
4616 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004617 }
4618
Richard Smithb1402ae2013-03-18 22:52:47 +00004619 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004620
Richard Smitha77a0a62011-08-15 21:04:07 +00004621 if (D.getDeclSpec().isConstexprSpecified())
4622 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4623 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004624
Douglas Gregord8f446f2010-07-13 06:37:01 +00004625 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4626 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4627 << D.getName().getSourceRange();
4628 return 0;
4629 }
4630
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004631 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004632 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004633
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004634 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004635 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004636
Richard Smith3f1b5d02011-05-05 21:57:07 +00004637 CheckTypedefForVariablyModifiedType(S, NewTD);
4638
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004639 bool Redeclaration = D.isRedeclaration();
4640 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4641 D.setRedeclaration(Redeclaration);
4642 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004643}
4644
Richard Smith3f1b5d02011-05-05 21:57:07 +00004645void
4646Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004647 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4648 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004649 // Note that variably modified types must be fixed before merging the decl so
4650 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004651 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4652 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004653 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004654 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004655
Chris Lattner9fecd742009-04-19 05:21:20 +00004656 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004657 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004658 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004659 TypeSourceInfo *FixedTInfo =
4660 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4661 SizeIsNegative,
4662 Oversized);
4663 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004664 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004665 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004666 } else {
4667 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004668 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004669 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004670 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004671 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004672 Diag(NewTD->getLocation(), diag::err_array_too_large)
4673 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004674 else
Richard Smithdda56e42011-04-15 14:24:37 +00004675 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004676 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004677 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004678 }
4679 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004680}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004681
Richard Smith3f1b5d02011-05-05 21:57:07 +00004682
4683/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4684/// declares a typedef-name, either using the 'typedef' type specifier or via
4685/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4686NamedDecl*
4687Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4688 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004689 // Merge the decl with the existing one if appropriate. If the decl is
4690 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004691 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4692 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004693 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004694 if (!Previous.empty()) {
4695 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004696 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004697 }
4698
Douglas Gregor27821ce2009-07-07 16:35:42 +00004699 // If this is the C FILE type, notify the AST context.
4700 if (IdentifierInfo *II = NewTD->getIdentifier())
4701 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004702 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004703 if (II->isStr("FILE"))
4704 Context.setFILEDecl(NewTD);
4705 else if (II->isStr("jmp_buf"))
4706 Context.setjmp_bufDecl(NewTD);
4707 else if (II->isStr("sigjmp_buf"))
4708 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004709 else if (II->isStr("ucontext_t"))
4710 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004711 }
4712
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004713 return NewTD;
4714}
4715
Douglas Gregor5d68a202009-02-24 19:23:27 +00004716/// \brief Determines whether the given declaration is an out-of-scope
4717/// previous declaration.
4718///
4719/// This routine should be invoked when name lookup has found a
4720/// previous declaration (PrevDecl) that is not in the scope where a
4721/// new declaration by the same name is being introduced. If the new
4722/// declaration occurs in a local scope, previous declarations with
4723/// linkage may still be considered previous declarations (C99
4724/// 6.2.2p4-5, C++ [basic.link]p6).
4725///
4726/// \param PrevDecl the previous declaration found by name
4727/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004728///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004729/// \param DC the context in which the new declaration is being
4730/// declared.
4731///
4732/// \returns true if PrevDecl is an out-of-scope previous declaration
4733/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004734static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004735isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4736 ASTContext &Context) {
4737 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004738 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004739
Douglas Gregoreddf4332009-02-24 20:03:32 +00004740 if (!PrevDecl->hasLinkage())
4741 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004742
David Blaikiebbafb8a2012-03-11 07:00:24 +00004743 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004744 // C++ [basic.link]p6:
4745 // If there is a visible declaration of an entity with linkage
4746 // having the same name and type, ignoring entities declared
4747 // outside the innermost enclosing namespace scope, the block
4748 // scope declaration declares that same entity and receives the
4749 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004750 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004751 if (!OuterContext->isFunctionOrMethod())
4752 // This rule only applies to block-scope declarations.
4753 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004754
4755 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4756 if (PrevOuterContext->isRecord())
4757 // We found a member function: ignore it.
4758 return false;
4759
4760 // Find the innermost enclosing namespace for the new and
4761 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004762 OuterContext = OuterContext->getEnclosingNamespaceContext();
4763 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004764
Douglas Gregorfcee9462010-08-27 22:55:10 +00004765 // The previous declaration is in a different namespace, so it
4766 // isn't the same function.
4767 if (!OuterContext->Equals(PrevOuterContext))
4768 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004769 }
4770
Douglas Gregor5d68a202009-02-24 19:23:27 +00004771 return true;
4772}
4773
John McCall3e11ebe2010-03-15 10:12:16 +00004774static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4775 CXXScopeSpec &SS = D.getCXXScopeSpec();
4776 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004777 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004778}
4779
John McCall31168b02011-06-15 23:02:42 +00004780bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4781 QualType type = decl->getType();
4782 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4783 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4784 // Various kinds of declaration aren't allowed to be __autoreleasing.
4785 unsigned kind = -1U;
4786 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4787 if (var->hasAttr<BlocksAttr>())
4788 kind = 0; // __block
4789 else if (!var->hasLocalStorage())
4790 kind = 1; // global
4791 } else if (isa<ObjCIvarDecl>(decl)) {
4792 kind = 3; // ivar
4793 } else if (isa<FieldDecl>(decl)) {
4794 kind = 2; // field
4795 }
4796
4797 if (kind != -1U) {
4798 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4799 << kind;
4800 }
4801 } else if (lifetime == Qualifiers::OCL_None) {
4802 // Try to infer lifetime.
4803 if (!type->isObjCLifetimeType())
4804 return false;
4805
4806 lifetime = type->getObjCARCImplicitLifetime();
4807 type = Context.getLifetimeQualifiedType(type, lifetime);
4808 decl->setType(type);
4809 }
4810
4811 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4812 // Thread-local variables cannot have lifetime.
4813 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004814 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004815 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004816 << var->getType();
4817 return true;
4818 }
4819 }
4820
4821 return false;
4822}
4823
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004824static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004825 // Ensure that an auto decl is deduced otherwise the checks below might cache
4826 // the wrong linkage.
4827 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4828
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004829 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004830 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004831 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004832 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4833 ND.dropAttr<WeakAttr>();
4834 }
4835 }
4836 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004837 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004838 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4839 ND.dropAttr<WeakRefAttr>();
4840 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004841 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004842
4843 // 'selectany' only applies to externally visible varable declarations.
4844 // It does not apply to functions.
4845 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4846 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4847 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4848 ND.dropAttr<SelectAnyAttr>();
4849 }
4850 }
Nico Rieck8ca0bfc2014-03-31 14:56:58 +00004851
4852 // dll attributes require external linkage.
4853 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
4854 if (!ND.isExternallyVisible()) {
4855 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4856 << &ND << Attr;
4857 ND.setInvalidDecl();
4858 }
4859 }
4860 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
4861 if (!ND.isExternallyVisible()) {
4862 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4863 << &ND << Attr;
4864 ND.setInvalidDecl();
4865 }
4866 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004867}
4868
Nico Rieck82f0b062014-03-31 14:56:15 +00004869static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
4870 NamedDecl *NewDecl,
4871 bool IsSpecialization) {
4872 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
4873 OldDecl = OldTD->getTemplatedDecl();
4874 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
4875 NewDecl = NewTD->getTemplatedDecl();
4876
4877 if (!OldDecl || !NewDecl)
4878 return;
4879
4880 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
4881 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
4882 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
4883 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
4884
4885 // dllimport and dllexport are inheritable attributes so we have to exclude
4886 // inherited attribute instances.
4887 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
4888 (NewExportAttr && !NewExportAttr->isInherited());
4889
4890 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
4891 // the only exception being explicit specializations.
4892 // Implicitly generated declarations are also excluded for now because there
4893 // is no other way to switch these to use dllimport or dllexport.
4894 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
4895 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
4896 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
4897 << NewDecl
4898 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
4899 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4900 NewDecl->setInvalidDecl();
4901 return;
4902 }
4903
4904 // A redeclaration is not allowed to drop a dllimport attribute, the only
4905 // exception being inline function definitions.
4906 // FIXME: Handle inline functions.
4907 // NB: MSVC converts such a declaration to dllexport.
4908 if (OldImportAttr && !HasNewAttr) {
4909 S.Diag(NewDecl->getLocation(),
4910 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4911 << NewDecl << OldImportAttr;
4912 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4913 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
4914 OldDecl->dropAttr<DLLImportAttr>();
4915 NewDecl->dropAttr<DLLImportAttr>();
4916 }
4917}
4918
John McCallc87d9722013-04-02 02:48:58 +00004919/// Given that we are within the definition of the given function,
4920/// will that definition behave like C99's 'inline', where the
4921/// definition is discarded except for optimization purposes?
4922static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4923 // Try to avoid calling GetGVALinkageForFunction.
4924
4925 // All cases of this require the 'inline' keyword.
4926 if (!FD->isInlined()) return false;
4927
4928 // This is only possible in C++ with the gnu_inline attribute.
4929 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4930 return false;
4931
4932 // Okay, go ahead and call the relatively-more-expensive function.
4933
4934#ifndef NDEBUG
4935 // AST quite reasonably asserts that it's working on a function
4936 // definition. We don't really have a way to tell it that we're
4937 // currently defining the function, so just lie to it in +Asserts
4938 // builds. This is an awful hack.
4939 FD->setLazyBody(1);
4940#endif
4941
David Majnemer27d69db2014-04-28 22:17:59 +00004942 bool isC99Inline =
4943 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
John McCallc87d9722013-04-02 02:48:58 +00004944
4945#ifndef NDEBUG
4946 FD->setLazyBody(0);
4947#endif
4948
4949 return isC99Inline;
4950}
4951
Richard Smithac974a32013-06-30 09:48:50 +00004952/// Determine whether a variable is extern "C" prior to attaching
4953/// an initializer. We can't just call isExternC() here, because that
4954/// will also compute and cache whether the declaration is externally
4955/// visible, which might change when we attach the initializer.
4956///
4957/// This can only be used if the declaration is known to not be a
4958/// redeclaration of an internal linkage declaration.
4959///
4960/// For instance:
4961///
4962/// auto x = []{};
4963///
4964/// Attaching the initializer here makes this declaration not externally
4965/// visible, because its type has internal linkage.
4966///
4967/// FIXME: This is a hack.
4968template<typename T>
4969static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4970 if (S.getLangOpts().CPlusPlus) {
4971 // In C++, the overloadable attribute negates the effects of extern "C".
4972 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4973 return false;
4974 }
4975 return D->isExternC();
4976}
4977
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004978static bool shouldConsiderLinkage(const VarDecl *VD) {
4979 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4980 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004981 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004982 if (DC->isFileContext())
4983 return true;
4984 if (DC->isRecord())
4985 return false;
4986 llvm_unreachable("Unexpected context");
4987}
4988
4989static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4990 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4991 if (DC->isFileContext() || DC->isFunctionOrMethod())
4992 return true;
4993 if (DC->isRecord())
4994 return false;
4995 llvm_unreachable("Unexpected context");
4996}
4997
Nico Riecke84f8db2014-03-23 21:24:01 +00004998static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
4999 AttributeList::Kind Kind) {
5000 for (const AttributeList *L = AttrList; L; L = L->getNext())
5001 if (L->getKind() == Kind)
5002 return true;
5003 return false;
5004}
5005
5006static bool hasParsedAttr(Scope *S, const Declarator &PD,
5007 AttributeList::Kind Kind) {
5008 // Check decl attributes on the DeclSpec.
5009 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5010 return true;
5011
5012 // Walk the declarator structure, checking decl attributes that were in a type
5013 // position to the decl itself.
5014 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5015 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5016 return true;
5017 }
5018
5019 // Finally, check attributes on the decl itself.
5020 return hasParsedAttr(S, PD.getAttributes(), Kind);
5021}
5022
Richard Smith541b38b2013-09-20 01:15:31 +00005023/// Adjust the \c DeclContext for a function or variable that might be a
5024/// function-local external declaration.
5025bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5026 if (!DC->isFunctionOrMethod())
5027 return false;
5028
5029 // If this is a local extern function or variable declared within a function
5030 // template, don't add it into the enclosing namespace scope until it is
5031 // instantiated; it might have a dependent type right now.
5032 if (DC->isDependentContext())
5033 return true;
5034
5035 // C++11 [basic.link]p7:
5036 // When a block scope declaration of an entity with linkage is not found to
5037 // refer to some other declaration, then that entity is a member of the
5038 // innermost enclosing namespace.
5039 //
5040 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5041 // semantically-enclosing namespace, not a lexically-enclosing one.
5042 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5043 DC = DC->getParent();
5044 return true;
5045}
5046
Larisse Voufo39a1e502013-08-06 01:03:05 +00005047NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00005048Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005049 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005050 MultiTemplateParamsArg TemplateParamLists,
5051 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005052 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005053 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005054
Douglas Gregorc4df4072010-04-19 22:54:31 +00005055 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00005056 VarDecl::StorageClass SC =
5057 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00005058
Nico Riecke84f8db2014-03-23 21:24:01 +00005059 // dllimport globals without explicit storage class are treated as extern. We
5060 // have to change the storage class this early to get the right DeclContext.
5061 if (SC == SC_None && !DC->isRecord() &&
5062 hasParsedAttr(S, D, AttributeList::AT_DLLImport))
5063 SC = SC_Extern;
5064
Richard Smith541b38b2013-09-20 01:15:31 +00005065 DeclContext *OriginalDC = DC;
5066 bool IsLocalExternDecl = SC == SC_Extern &&
5067 adjustContextForLocalExternDecl(DC);
5068
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005069 if (getLangOpts().OpenCL) {
5070 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5071 QualType NR = R;
5072 while (NR->isPointerType()) {
5073 if (NR->isFunctionPointerType()) {
5074 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5075 D.setInvalidType();
5076 break;
5077 }
5078 NR = NR->getPointeeType();
5079 }
5080
5081 if (!getOpenCLOptions().cl_khr_fp16) {
5082 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5083 // half array type (unless the cl_khr_fp16 extension is enabled).
5084 if (Context.getBaseElementType(R)->isHalfType()) {
5085 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5086 D.setInvalidType();
5087 }
Joey Goulydd7f4562013-01-23 11:56:20 +00005088 }
5089 }
5090
Douglas Gregorc4df4072010-04-19 22:54:31 +00005091 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005092 // mutable can only appear on non-static class members, so it's always
5093 // an error here
5094 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005095 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005096 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005097 }
John McCallc87d9722013-04-02 02:48:58 +00005098
Richard Smithf2c9afc2013-06-17 01:34:01 +00005099 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5100 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5101 D.getDeclSpec().getStorageClassSpecLoc())) {
5102 // In C++11, the 'register' storage class specifier is deprecated.
5103 // Suppress the warning in system macros, it's used in macros in some
5104 // popular C system headers, such as in glibc's htonl() macro.
5105 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5106 diag::warn_deprecated_register)
5107 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5108 }
5109
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005110 IdentifierInfo *II = Name.getAsIdentifierInfo();
5111 if (!II) {
5112 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005113 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005114 return 0;
5115 }
5116
Richard Smithb1402ae2013-03-18 22:52:47 +00005117 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005118
Douglas Gregor212cab32009-03-11 20:22:50 +00005119 if (!DC->isRecord() && S->getFnParent() == 0) {
5120 // C99 6.9p2: The storage-class specifiers auto and register shall not
5121 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005122 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005123 // If this is a register variable with an asm label specified, then this
5124 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005125 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005126 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5127 else
5128 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005129 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005130 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005131 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005132
David Blaikiebbafb8a2012-03-11 07:00:24 +00005133 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005134 // Set up the special work-group-local storage class for variables in the
5135 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005136 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005137 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005138 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005139
Guy Benyei61054192013-02-07 10:55:47 +00005140 // OpenCL v1.2 s6.9.b p4:
5141 // The sampler type cannot be used with the __local and __global address
5142 // space qualifiers.
5143 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5144 R.getAddressSpace() == LangAS::opencl_global)) {
5145 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5146 }
5147
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005148 // OpenCL 1.2 spec, p6.9 r:
5149 // The event type cannot be used to declare a program scope variable.
5150 // The event type cannot be used with the __local, __constant and __global
5151 // address space qualifiers.
5152 if (R->isEventT()) {
5153 if (S->getParent() == 0) {
5154 Diag(D.getLocStart(), diag::err_event_t_global_var);
5155 D.setInvalidType();
5156 }
5157
5158 if (R.getAddressSpace()) {
5159 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5160 D.setInvalidType();
5161 }
5162 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005163 }
5164
Larisse Voufo39a1e502013-08-06 01:03:05 +00005165 bool IsExplicitSpecialization = false;
5166 bool IsVariableTemplateSpecialization = false;
5167 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005168 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005169 VarDecl *NewVD = 0;
5170 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005171 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005172 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005173 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005174 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005175 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005176
5177 if (D.isInvalidType())
5178 NewVD->setInvalidDecl();
5179 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005180 bool Invalid = false;
5181
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005182 if (DC->isRecord() && !CurContext->isRecord()) {
5183 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005184 switch (SC) {
5185 case SC_None:
5186 break;
5187 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005188 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5189 diag::err_static_out_of_line)
5190 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005191 break;
5192 case SC_Auto:
5193 case SC_Register:
5194 case SC_Extern:
5195 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5196 // to names of variables declared in a block or to function parameters.
5197 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5198 // of class members
5199
5200 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5201 diag::err_storage_class_for_static_member)
5202 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5203 break;
5204 case SC_PrivateExtern:
5205 llvm_unreachable("C storage class in c++!");
5206 case SC_OpenCLWorkGroupLocal:
5207 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005208 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005209 }
5210
Richard Smith42973752012-02-16 20:41:22 +00005211 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005212 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5213 if (RD->isLocalClass())
5214 Diag(D.getIdentifierLoc(),
5215 diag::err_static_data_member_not_allowed_in_local_class)
5216 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005217
Richard Smith42973752012-02-16 20:41:22 +00005218 // C++98 [class.union]p1: If a union contains a static data member,
5219 // the program is ill-formed. C++11 drops this restriction.
5220 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005221 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005222 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005223 ? diag::warn_cxx98_compat_static_data_member_in_union
5224 : diag::ext_static_data_member_in_union) << Name;
5225 // We conservatively disallow static data members in anonymous structs.
5226 else if (!RD->getDeclName())
5227 Diag(D.getIdentifierLoc(),
5228 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005229 << Name << RD->isUnion();
5230 }
5231 }
5232
5233 // Match up the template parameter lists with the scope specifier, then
5234 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005235 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5236 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00005237 D.getCXXScopeSpec(),
5238 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5239 ? D.getName().TemplateId
5240 : 0,
5241 TemplateParamLists,
Richard Smithbeef3452014-01-16 23:39:20 +00005242 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005243
Richard Smithbeef3452014-01-16 23:39:20 +00005244 if (TemplateParams) {
5245 if (!TemplateParams->size() &&
5246 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5247 // There is an extraneous 'template<>' for this variable. Complain
5248 // about it, but allow the declaration of the variable.
5249 Diag(TemplateParams->getTemplateLoc(),
5250 diag::err_template_variable_noparams)
5251 << II
5252 << SourceRange(TemplateParams->getTemplateLoc(),
5253 TemplateParams->getRAngleLoc());
5254 TemplateParams = 0;
5255 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005256 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5257 // This is an explicit specialization or a partial specialization.
5258 // FIXME: Check that we can declare a specialization here.
5259 IsVariableTemplateSpecialization = true;
5260 IsPartialSpecialization = TemplateParams->size() > 0;
5261 } else { // if (TemplateParams->size() > 0)
5262 // This is a template declaration.
5263 IsVariableTemplate = true;
5264
5265 // Check that we can declare a template here.
5266 if (CheckTemplateDeclScope(S, TemplateParams))
5267 return 0;
Richard Smith0d963d62014-04-17 02:56:49 +00005268
5269 // Only C++1y supports variable templates (N3651).
5270 Diag(D.getIdentifierLoc(),
5271 getLangOpts().CPlusPlus1y
5272 ? diag::warn_cxx11_compat_variable_template
5273 : diag::ext_variable_template);
Richard Smithbeef3452014-01-16 23:39:20 +00005274 }
5275 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00005276 } else {
5277 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5278 "should have a 'template<>' for this decl");
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
Larisse Voufo39a1e502013-08-06 01:03:05 +00005281 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005282 SourceLocation TemplateKWLoc =
5283 TemplateParamLists.size() > 0
5284 ? TemplateParamLists[0]->getTemplateLoc()
5285 : SourceLocation();
5286 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005287 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005288 IsPartialSpecialization);
5289 if (Res.isInvalid())
5290 return 0;
5291 NewVD = cast<VarDecl>(Res.get());
5292 AddToScope = false;
5293 } else
5294 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5295 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005296
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005297 // If this is supposed to be a variable template, create it as such.
5298 if (IsVariableTemplate) {
5299 NewTemplate =
5300 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005301 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005302 NewVD->setDescribedVarTemplate(NewTemplate);
5303 }
5304
Richard Smithb2bc2e62011-02-21 20:05:19 +00005305 // If this decl has an auto type in need of deduction, make a note of the
5306 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005307 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005308 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005309
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005310 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005311 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005312 if (NewTemplate)
5313 NewTemplate->setInvalidDecl();
5314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005316 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005317
Richard Smith72db5632014-01-25 21:32:06 +00005318 // If we have any template parameter lists that don't directly belong to
5319 // the variable (matching the scope specifier), store them.
5320 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5321 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005322 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005323 Context, TemplateParamLists.size() - VDTemplateParamLists,
5324 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005325
Richard Smith6331c402012-02-13 22:16:19 +00005326 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005327 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005328 }
5329
Douglas Gregor41866812011-09-12 18:37:38 +00005330 // Set the lexical context. If the declarator has a C++ scope specifier, the
5331 // lexical context will be different from the semantic context.
5332 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005333 if (NewTemplate)
5334 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005335
Richard Smith541b38b2013-09-20 01:15:31 +00005336 if (IsLocalExternDecl)
5337 NewVD->setLocalExternDecl();
5338
Richard Smithb4a9e862013-04-12 22:46:28 +00005339 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005340 if (NewVD->hasLocalStorage()) {
5341 // C++11 [dcl.stc]p4:
5342 // When thread_local is applied to a variable of block scope the
5343 // storage-class-specifier static is implied if it does not appear
5344 // explicitly.
5345 // Core issue: 'static' is not implied if the variable is declared
5346 // 'extern'.
5347 if (SCSpec == DeclSpec::SCS_unspecified &&
5348 TSCS == DeclSpec::TSCS_thread_local &&
5349 DC->isFunctionOrMethod())
5350 NewVD->setTSCSpec(TSCS);
5351 else
5352 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5353 diag::err_thread_non_global)
5354 << DeclSpec::getSpecifierName(TSCS);
5355 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005356 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5357 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005358 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005359 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005360 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005361
John McCallc87d9722013-04-02 02:48:58 +00005362 // C99 6.7.4p3
5363 // An inline definition of a function with external linkage shall
5364 // not contain a definition of a modifiable object with static or
5365 // thread storage duration...
5366 // We only apply this when the function is required to be defined
5367 // elsewhere, i.e. when the function is not 'extern inline'. Note
5368 // that a local variable with thread storage duration still has to
5369 // be marked 'static'. Also note that it's possible to get these
5370 // semantics in C++ using __attribute__((gnu_inline)).
5371 if (SC == SC_Static && S->getFnParent() != 0 &&
5372 !NewVD->getType().isConstQualified()) {
5373 FunctionDecl *CurFD = getCurFunctionDecl();
5374 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5375 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5376 diag::warn_static_local_in_extern_inline);
5377 MaybeSuggestAddingStaticToDecl(CurFD);
5378 }
5379 }
5380
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005381 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005382 if (IsVariableTemplateSpecialization)
5383 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5384 << (IsPartialSpecialization ? 1 : 0)
5385 << FixItHint::CreateRemoval(
5386 D.getDeclSpec().getModulePrivateSpecLoc());
5387 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005388 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5389 << 2
5390 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005391 else if (NewVD->hasLocalStorage())
5392 Diag(NewVD->getLocation(), diag::err_module_private_local)
5393 << 0 << NewVD->getDeclName()
5394 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5395 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005396 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005397 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005398 if (NewTemplate)
5399 NewTemplate->setModulePrivate();
5400 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005401 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005402
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005403 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005404 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005405
Peter Collingbournec6b08572012-08-28 20:37:50 +00005406 if (getLangOpts().CUDA) {
5407 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5408 // storage [duration]."
5409 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005410 (NewVD->hasAttr<CUDASharedAttr>() ||
5411 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005412 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005413 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005414 }
5415
Nico Riecke84f8db2014-03-23 21:24:01 +00005416 // Ensure that dllimport globals without explicit storage class are treated as
5417 // extern. The storage class is set above using parsed attributes. Now we can
5418 // check the VarDecl itself.
5419 assert(!NewVD->hasAttr<DLLImportAttr>() ||
5420 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5421 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5422
John McCall31168b02011-06-15 23:02:42 +00005423 // In auto-retain/release, infer strong retension for variables of
5424 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005425 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005426 NewVD->setInvalidDecl();
5427
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005428 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005429 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005430 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005431 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005432 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005433 if (S->getFnParent() != 0) {
5434 switch (SC) {
5435 case SC_None:
5436 case SC_Auto:
5437 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5438 break;
5439 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005440 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005441 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5442 break;
5443 case SC_Static:
5444 case SC_Extern:
5445 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005446 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005447 break;
5448 }
5449 }
5450
5451 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005452 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005453 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5454 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5455 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5456 if (I != ExtnameUndeclaredIdentifiers.end()) {
5457 NewVD->addAttr(I->second);
5458 ExtnameUndeclaredIdentifiers.erase(I);
5459 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005460 }
5461
John McCalla2a3f7d2010-03-16 21:48:18 +00005462 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005463 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005464 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005465
John McCall1f82f242009-11-18 22:49:29 +00005466 // Don't consider existing declarations that are in a different
5467 // scope and are out-of-semantic-context declarations (if the new
5468 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005469 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5470 D.getCXXScopeSpec().isNotEmpty() ||
5471 IsExplicitSpecialization ||
5472 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005473
Richard Smith1c34fb72013-08-13 18:18:50 +00005474 // Check whether the previous declaration is in the same block scope. This
5475 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5476 if (getLangOpts().CPlusPlus &&
5477 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5478 NewVD->setPreviousDeclInSameBlockScope(
5479 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005480 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005481
David Blaikiebbafb8a2012-03-11 07:00:24 +00005482 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005483 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5484 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005485 // If this is an explicit specialization of a static data member, check it.
5486 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5487 CheckMemberSpecialization(NewVD, Previous))
5488 NewVD->setInvalidDecl();
5489
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005490 // Merge the decl with the existing one if appropriate.
5491 if (!Previous.empty()) {
5492 if (Previous.isSingleResult() &&
5493 isa<FieldDecl>(Previous.getFoundDecl()) &&
5494 D.getCXXScopeSpec().isSet()) {
5495 // The user tried to define a non-static data member
5496 // out-of-line (C++ [dcl.meaning]p1).
5497 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5498 << D.getCXXScopeSpec().getRange();
5499 Previous.clear();
5500 NewVD->setInvalidDecl();
5501 }
5502 } else if (D.getCXXScopeSpec().isSet()) {
5503 // No previous declaration in the qualifying scope.
5504 Diag(D.getIdentifierLoc(), diag::err_no_member)
5505 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005506 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005507 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005508 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005509
Richard Smithbeef3452014-01-16 23:39:20 +00005510 if (!IsVariableTemplateSpecialization)
5511 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005512
Richard Smithbeef3452014-01-16 23:39:20 +00005513 if (NewTemplate) {
5514 VarTemplateDecl *PrevVarTemplate =
5515 NewVD->getPreviousDecl()
5516 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5517 : 0;
5518
5519 // Check the template parameter list of this declaration, possibly
5520 // merging in the template parameter list from the previous variable
5521 // template declaration.
5522 if (CheckTemplateParameterList(
5523 TemplateParams,
5524 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5525 : 0,
5526 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5527 DC->isDependentContext())
5528 ? TPC_ClassTemplateMember
5529 : TPC_VarTemplate))
5530 NewVD->setInvalidDecl();
5531
5532 // If we are providing an explicit specialization of a static variable
5533 // template, make a note of that.
5534 if (PrevVarTemplate &&
5535 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5536 PrevVarTemplate->setMemberSpecialization();
5537 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005538 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005539
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005540 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005541
Richard Smithac974a32013-06-30 09:48:50 +00005542 // If this is the first declaration of an extern C variable, update
5543 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005544 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005545 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005546 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005547
Reid Klecknerd8110b62013-09-10 20:14:30 +00005548 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005549 Decl *ManglingContextDecl;
5550 if (MangleNumberingContext *MCtx =
5551 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5552 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005553 Context.setManglingNumber(
5554 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005555 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005556 }
5557 }
5558
Nico Rieck82f0b062014-03-31 14:56:15 +00005559 if (D.isRedeclaration() && !Previous.empty()) {
5560 checkDLLAttributeRedeclaration(
5561 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5562 IsExplicitSpecialization);
5563 }
5564
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005565 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005566 if (NewVD->isInvalidDecl())
5567 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005568 ActOnDocumentableDecl(NewTemplate);
5569 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005570 }
5571
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005572 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005573}
5574
John McCalldf8b37c2010-03-22 09:20:08 +00005575/// \brief Diagnose variable or built-in function shadowing. Implements
5576/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005577///
John McCalldf8b37c2010-03-22 09:20:08 +00005578/// This method is called whenever a VarDecl is added to a "useful"
5579/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005580///
John McCall2d8c7602010-03-20 04:12:52 +00005581/// \param S the scope in which the shadowing name is being declared
5582/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005583///
John McCalldf8b37c2010-03-22 09:20:08 +00005584void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005585 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005586 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005587 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005588 return;
5589
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005590 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005591 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005592 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005593
5594 DeclContext *NewDC = D->getDeclContext();
5595
John McCall2d8c7602010-03-20 04:12:52 +00005596 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005597 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005598 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005599
John McCalla2a3f7d2010-03-16 21:48:18 +00005600 NamedDecl* ShadowedDecl = R.getFoundDecl();
5601 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5602 return;
5603
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005604 // Fields are not shadowed by variables in C++ static methods.
5605 if (isa<FieldDecl>(ShadowedDecl))
5606 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5607 if (MD->isStatic())
5608 return;
5609
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005610 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5611 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005612 // For shadowing external vars, make sure that we point to the global
5613 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005614 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005615 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005616 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005617 break;
5618 }
5619 }
5620
5621 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5622
John McCall2d8c7602010-03-20 04:12:52 +00005623 // Only warn about certain kinds of shadowing for class members.
5624 if (NewDC && NewDC->isRecord()) {
5625 // In particular, don't warn about shadowing non-class members.
5626 if (!OldDC->isRecord())
5627 return;
5628
5629 // TODO: should we warn about static data members shadowing
5630 // static data members from base classes?
5631
5632 // TODO: don't diagnose for inaccessible shadowed members.
5633 // This is hard to do perfectly because we might friend the
5634 // shadowing context, but that's just a false negative.
5635 }
5636
5637 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005638 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005639 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005640 if (isa<FieldDecl>(ShadowedDecl))
5641 Kind = 3; // field
5642 else
5643 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005644 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005645 Kind = 1; // global
5646 else
5647 Kind = 0; // local
5648
John McCall2d8c7602010-03-20 04:12:52 +00005649 DeclarationName Name = R.getLookupName();
5650
John McCalla2a3f7d2010-03-16 21:48:18 +00005651 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005652 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5653 return;
John McCall2d8c7602010-03-20 04:12:52 +00005654 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005655 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5656}
5657
John McCalldf8b37c2010-03-22 09:20:08 +00005658/// \brief Check -Wshadow without the advantage of a previous lookup.
5659void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005660 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005661 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005662 return;
5663
John McCalldf8b37c2010-03-22 09:20:08 +00005664 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5665 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5666 LookupName(R, S);
5667 CheckShadow(S, D, R);
5668}
5669
Richard Smithac974a32013-06-30 09:48:50 +00005670/// Check for conflict between this global or extern "C" declaration and
5671/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005672template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005673static bool checkGlobalOrExternCConflict(
5674 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5675 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5676 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005677
Richard Smithac974a32013-06-30 09:48:50 +00005678 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5679 // The common case: this global doesn't conflict with any extern "C"
5680 // declaration.
5681 return false;
5682 }
5683
5684 if (Prev) {
5685 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5686 // Both the old and new declarations have C language linkage. This is a
5687 // redeclaration.
5688 Previous.clear();
5689 Previous.addDecl(Prev);
5690 return true;
5691 }
5692
5693 // This is a global, non-extern "C" declaration, and there is a previous
5694 // non-global extern "C" declaration. Diagnose if this is a variable
5695 // declaration.
5696 if (!isa<VarDecl>(ND))
5697 return false;
5698 } else {
5699 // The declaration is extern "C". Check for any declaration in the
5700 // translation unit which might conflict.
5701 if (IsGlobal) {
5702 // We have already performed the lookup into the translation unit.
5703 IsGlobal = false;
5704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5705 I != E; ++I) {
5706 if (isa<VarDecl>(*I)) {
5707 Prev = *I;
5708 break;
5709 }
5710 }
5711 } else {
5712 DeclContext::lookup_result R =
5713 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5714 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5715 I != E; ++I) {
5716 if (isa<VarDecl>(*I)) {
5717 Prev = *I;
5718 break;
5719 }
5720 // FIXME: If we have any other entity with this name in global scope,
5721 // the declaration is ill-formed, but that is a defect: it breaks the
5722 // 'stat' hack, for instance. Only variables can have mangled name
5723 // clashes with extern "C" declarations, so only they deserve a
5724 // diagnostic.
5725 }
5726 }
5727
5728 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005729 return false;
5730 }
5731
Richard Smithac974a32013-06-30 09:48:50 +00005732 // Use the first declaration's location to ensure we point at something which
5733 // is lexically inside an extern "C" linkage-spec.
5734 assert(Prev && "should have found a previous declaration to diagnose");
5735 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005736 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005737 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005738 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005739
5740 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5741 << IsGlobal << ND;
5742 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5743 << IsGlobal;
5744 return false;
5745}
5746
5747/// Apply special rules for handling extern "C" declarations. Returns \c true
5748/// if we have found that this is a redeclaration of some prior entity.
5749///
5750/// Per C++ [dcl.link]p6:
5751/// Two declarations [for a function or variable] with C language linkage
5752/// with the same name that appear in different scopes refer to the same
5753/// [entity]. An entity with C language linkage shall not be declared with
5754/// the same name as an entity in global scope.
5755template<typename T>
5756static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5757 LookupResult &Previous) {
5758 if (!S.getLangOpts().CPlusPlus) {
5759 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005760 // variable declared in function scope. We don't need this in C++, because
5761 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005762 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5763 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5764 Previous.clear();
5765 Previous.addDecl(Prev);
5766 return true;
5767 }
5768 }
5769 return false;
5770 }
5771
5772 // A declaration in the translation unit can conflict with an extern "C"
5773 // declaration.
5774 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5775 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5776
5777 // An extern "C" declaration can conflict with a declaration in the
5778 // translation unit or can be a redeclaration of an extern "C" declaration
5779 // in another scope.
5780 if (isIncompleteDeclExternC(S,ND))
5781 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5782
5783 // Neither global nor extern "C": nothing to do.
5784 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005785}
5786
Richard Smith27d807c2013-04-30 13:56:41 +00005787void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005788 // If the decl is already known invalid, don't check it.
5789 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005790 return;
Mike Stump11289f42009-09-09 15:08:12 +00005791
Abramo Bagnara341ab732012-11-08 14:44:42 +00005792 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5793 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005794
Richard Smith27d807c2013-04-30 13:56:41 +00005795 // Defer checking an 'auto' type until its initializer is attached.
5796 if (T->isUndeducedType())
5797 return;
5798
Richard Smithdc4ccaa2014-03-27 01:22:48 +00005799 if (NewVD->hasAttrs())
5800 CheckAlignasUnderalignment(NewVD);
5801
John McCall8b07ec22010-05-15 11:32:37 +00005802 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005803 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5804 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005805 T = Context.getObjCObjectPointerType(T);
5806 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005807 }
Mike Stump11289f42009-09-09 15:08:12 +00005808
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005809 // Emit an error if an address space was applied to decl with local storage.
5810 // This includes arrays of objects with address space qualifiers, but not
5811 // automatic variables that point to other address spaces.
5812 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005813 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005814 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005815 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005816 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005817 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005818
Tanya Lattner713eef42013-04-05 20:14:50 +00005819 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5820 // __constant address space.
5821 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5822 && T.getAddressSpace() != LangAS::opencl_constant
5823 && !T->isSamplerT()){
5824 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5825 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005826 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005827 }
5828
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005829 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5830 // scope.
5831 if ((getLangOpts().OpenCLVersion >= 120)
5832 && NewVD->isStaticLocal()) {
5833 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5834 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005835 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005836 }
5837
Mike Stumpca5ae662009-04-14 00:57:29 +00005838 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005839 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005840 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005841 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005842 else {
5843 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005844 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005845 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005846 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005847
Chris Lattner9fecd742009-04-19 05:21:20 +00005848 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005849 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005850 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005851 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005852
Chris Lattner9fecd742009-04-19 05:21:20 +00005853 if ((isVM && NewVD->hasLinkage()) ||
5854 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005855 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005856 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005857 TypeSourceInfo *FixedTInfo =
5858 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5859 SizeIsNegative, Oversized);
5860 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005861 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005862 // FIXME: This won't give the correct result for
5863 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005864 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005865
Anders Carlsson6c885802009-02-28 21:56:50 +00005866 if (NewVD->isFileVarDecl())
5867 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005868 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005869 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005870 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005871 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005872 else
5873 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005874 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005875 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005876 return;
Mike Stump11289f42009-09-09 15:08:12 +00005877 }
5878
Abramo Bagnara341ab732012-11-08 14:44:42 +00005879 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005880 if (NewVD->isFileVarDecl())
5881 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5882 else
5883 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005884 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005885 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005886 }
Mike Stump11289f42009-09-09 15:08:12 +00005887
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005888 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005889 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005890 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005891 }
5892
David Majnemer0ffa3312013-05-29 00:56:45 +00005893 if (T->isVoidType()) {
5894 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5895 // of objects and functions.
5896 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5897 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5898 << T;
5899 NewVD->setInvalidDecl();
5900 return;
5901 }
Richard Smith27d807c2013-04-30 13:56:41 +00005902 }
5903
5904 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5905 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5906 NewVD->setInvalidDecl();
5907 return;
5908 }
5909
5910 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5911 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5912 NewVD->setInvalidDecl();
5913 return;
5914 }
5915
5916 if (NewVD->isConstexpr() && !T->isDependentType() &&
5917 RequireLiteralType(NewVD->getLocation(), T,
5918 diag::err_constexpr_var_non_literal)) {
Richard Smith27d807c2013-04-30 13:56:41 +00005919 NewVD->setInvalidDecl();
5920 return;
5921 }
5922}
5923
5924/// \brief Perform semantic checking on a newly-created variable
5925/// declaration.
5926///
5927/// This routine performs all of the type-checking required for a
5928/// variable declaration once it has been built. It is used both to
5929/// check variables after they have been parsed and their declarators
5930/// have been translated into a declaration, and to check variables
5931/// that have been instantiated from a template.
5932///
5933/// Sets NewVD->isInvalidDecl() if an error was encountered.
5934///
5935/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005936bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005937 CheckVariableDeclarationType(NewVD);
5938
5939 // If the decl is already known invalid, don't check it.
5940 if (NewVD->isInvalidDecl())
5941 return false;
5942
John McCallb65e8fe2013-04-01 18:34:28 +00005943 // If we did not find anything by this name, look for a non-visible
5944 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005945 if (Previous.empty() &&
5946 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005947 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005948
Douglas Gregor3552dab2013-01-09 00:47:56 +00005949 // Filter out any non-conflicting previous declarations.
5950 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5951
John McCall1f82f242009-11-18 22:49:29 +00005952 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005953 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005954 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005955 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005956 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005957}
5958
Douglas Gregor36d1b142009-10-06 17:59:45 +00005959/// \brief Data used with FindOverriddenMethod
5960struct FindOverriddenMethodData {
5961 Sema *S;
5962 CXXMethodDecl *Method;
5963};
5964
5965/// \brief Member lookup function that determines whether a given C++
5966/// method overrides a method in a base class, to be used with
5967/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005968static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005969 CXXBasePath &Path,
5970 void *UserData) {
5971 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005972
Douglas Gregor36d1b142009-10-06 17:59:45 +00005973 FindOverriddenMethodData *Data
5974 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005975
5976 DeclarationName Name = Data->Method->getDeclName();
5977
5978 // FIXME: Do we care about other names here too?
5979 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005980 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005981 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5982 CanQualType CT = Data->S->Context.getCanonicalType(T);
5983
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005984 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005985 }
5986
5987 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005988 !Path.Decls.empty();
5989 Path.Decls = Path.Decls.slice(1)) {
5990 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005991 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5992 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005993 return true;
5994 }
5995 }
5996
5997 return false;
5998}
5999
David Blaikie7e414262012-10-17 00:47:58 +00006000namespace {
6001 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6002}
6003/// \brief Report an error regarding overriding, along with any relevant
6004/// overriden methods.
6005///
6006/// \param DiagID the primary error to report.
6007/// \param MD the overriding method.
6008/// \param OEK which overrides to include as notes.
6009static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6010 OverrideErrorKind OEK = OEK_All) {
6011 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6012 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6013 E = MD->end_overridden_methods();
6014 I != E; ++I) {
6015 // This check (& the OEK parameter) could be replaced by a predicate, but
6016 // without lambdas that would be overkill. This is still nicer than writing
6017 // out the diag loop 3 times.
6018 if ((OEK == OEK_All) ||
6019 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6020 (OEK == OEK_Deleted && (*I)->isDeleted()))
6021 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6022 }
6023}
6024
Sebastian Redld5b24532009-11-18 21:51:29 +00006025/// AddOverriddenMethods - See if a method overrides any in the base classes,
6026/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006027bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00006028 // Look for virtual methods in base classes that this method might override.
6029 CXXBasePaths Paths;
6030 FindOverriddenMethodData Data;
6031 Data.Method = MD;
6032 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00006033 bool hasDeletedOverridenMethods = false;
6034 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006035 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00006036 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
Aaron Ballmane6f465e2014-03-14 21:38:48 +00006037 for (auto *I : Paths.found_decls()) {
6038 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00006039 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00006040 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00006041 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00006042 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00006043 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00006044 hasDeletedOverridenMethods |= OldMD->isDeleted();
6045 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006046 AddedAny = true;
6047 }
Sebastian Redld5b24532009-11-18 21:51:29 +00006048 }
6049 }
6050 }
David Blaikie7e414262012-10-17 00:47:58 +00006051
6052 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6053 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6054 }
6055 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6056 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6057 }
6058
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006059 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00006060}
6061
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006062namespace {
6063 // Struct for holding all of the extra arguments needed by
6064 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6065 struct ActOnFDArgs {
6066 Scope *S;
6067 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006068 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006069 bool AddToScope;
6070 };
6071}
6072
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006073namespace {
6074
6075// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006076// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006077class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6078 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006079 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6080 CXXRecordDecl *Parent)
6081 : Context(Context), OriginalFD(TypoFD),
6082 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006083
Craig Toppere14c0f82014-03-12 04:55:44 +00006084 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006085 if (candidate.getEditDistance() == 0)
6086 return false;
6087
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006088 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006089 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6090 CDeclEnd = candidate.end();
6091 CDecl != CDeclEnd; ++CDecl) {
6092 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6093
6094 if (FD && !FD->hasBody() &&
6095 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6096 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6097 CXXRecordDecl *Parent = MD->getParent();
6098 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6099 return true;
6100 } else if (!ExpectedParent) {
6101 return true;
6102 }
6103 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006104 }
6105
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006106 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006107 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006108
6109 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006110 ASTContext &Context;
6111 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006112 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006113};
6114
6115}
6116
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006117/// \brief Generate diagnostics for an invalid function redeclaration.
6118///
6119/// This routine handles generating the diagnostic messages for an invalid
6120/// function redeclaration, including finding possible similar declarations
6121/// or performing typo correction if there are no previous declarations with
6122/// the same name.
6123///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006124/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006125/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006126static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006127 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006128 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006129 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006130 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006131 SmallVector<unsigned, 1> MismatchedParams;
6132 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006133 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006134 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006135 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6136 : diag::err_member_decl_does_not_match;
6137 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6138 IsLocalFriend ? Sema::LookupLocalFriendName
6139 : Sema::LookupOrdinaryName,
6140 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006141
6142 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006143 if (IsLocalFriend)
6144 SemaRef.LookupName(Prev, S);
6145 else
6146 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006147 assert(!Prev.isAmbiguous() &&
6148 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006149 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006150 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6151 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006152 if (!Prev.empty()) {
6153 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6154 Func != FuncEnd; ++Func) {
6155 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006156 if (FD &&
6157 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006158 // Add 1 to the index so that 0 can mean the mismatch didn't
6159 // involve a parameter
6160 unsigned ParamNum =
6161 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6162 NearMatches.push_back(std::make_pair(FD, ParamNum));
6163 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006164 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006165 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006166 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006167 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6168 &ExtraArgs.D.getCXXScopeSpec(), Validator,
John Thompson2255f2c2014-04-23 12:57:01 +00006169 Sema::CTK_ErrorRecovery, IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006170 // Set up everything for the call to ActOnFunctionDeclarator
6171 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6172 ExtraArgs.D.getIdentifierLoc());
6173 Previous.clear();
6174 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006175 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6176 CDeclEnd = Correction.end();
6177 CDecl != CDeclEnd; ++CDecl) {
6178 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006179 if (FD && !FD->hasBody() &&
6180 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006181 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006182 }
6183 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006184 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006185
6186 NamedDecl *Result;
6187 // Retry building the function declaration with the new previous
6188 // declarations, and with errors suppressed.
6189 {
6190 // Trap errors.
6191 Sema::SFINAETrap Trap(SemaRef);
6192
6193 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6194 // pieces need to verify the typo-corrected C++ declaration and hopefully
6195 // eliminate the need for the parameter pack ExtraArgs.
6196 Result = SemaRef.ActOnFunctionDeclarator(
6197 ExtraArgs.S, ExtraArgs.D,
6198 Correction.getCorrectionDecl()->getDeclContext(),
6199 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6200 ExtraArgs.AddToScope);
6201
6202 if (Trap.hasErrorOccurred())
6203 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006204 }
Richard Smithf9b15102013-08-17 00:46:16 +00006205
6206 if (Result) {
6207 // Determine which correction we picked.
6208 Decl *Canonical = Result->getCanonicalDecl();
6209 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6210 I != E; ++I)
6211 if ((*I)->getCanonicalDecl() == Canonical)
6212 Correction.setCorrectionDecl(*I);
6213
6214 SemaRef.diagnoseTypo(
6215 Correction,
6216 SemaRef.PDiag(IsLocalFriend
6217 ? diag::err_no_matching_local_friend_suggest
6218 : diag::err_member_decl_does_not_match_suggest)
6219 << Name << NewDC << IsDefinition);
6220 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006221 }
Richard Smithf9b15102013-08-17 00:46:16 +00006222
6223 // Pretend the typo correction never occurred
6224 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6225 ExtraArgs.D.getIdentifierLoc());
6226 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6227 Previous.clear();
6228 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006229 }
6230
Richard Smithf9b15102013-08-17 00:46:16 +00006231 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6232 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006233
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006234 bool NewFDisConst = false;
6235 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006236 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006237
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006238 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006239 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6240 NearMatch != NearMatchEnd; ++NearMatch) {
6241 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006242 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6243 bool FDisConst = MD && MD->isConst();
6244 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006245
Richard Smith541b38b2013-09-20 01:15:31 +00006246 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006247 if (unsigned Idx = NearMatch->second) {
6248 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006249 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6250 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006251 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6252 : diag::note_local_decl_close_param_match)
6253 << Idx << FDParam->getType()
6254 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006255 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006256 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006257 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006258 } else
Richard Smith114394f2013-08-09 04:35:01 +00006259 SemaRef.Diag(FD->getLocation(),
6260 IsMember ? diag::note_member_def_close_match
6261 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006262 }
Richard Smithf9b15102013-08-17 00:46:16 +00006263 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006264}
6265
David Blaikie30d15442011-10-19 22:56:21 +00006266static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6267 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006268 switch (D.getDeclSpec().getStorageClassSpec()) {
6269 default: llvm_unreachable("Unknown storage class!");
6270 case DeclSpec::SCS_auto:
6271 case DeclSpec::SCS_register:
6272 case DeclSpec::SCS_mutable:
6273 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6274 diag::err_typecheck_sclass_func);
6275 D.setInvalidType();
6276 break;
6277 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006278 case DeclSpec::SCS_extern:
6279 if (D.getDeclSpec().isExternInLinkageSpec())
6280 return SC_None;
6281 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006282 case DeclSpec::SCS_static: {
6283 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6284 // C99 6.7.1p5:
6285 // The declaration of an identifier for a function that has
6286 // block scope shall have no explicit storage-class specifier
6287 // other than extern
6288 // See also (C++ [dcl.stc]p4).
6289 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6290 diag::err_static_block_func);
6291 break;
6292 } else
6293 return SC_Static;
6294 }
6295 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6296 }
6297
6298 // No explicit storage class has already been returned
6299 return SC_None;
6300}
6301
6302static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6303 DeclContext *DC, QualType &R,
6304 TypeSourceInfo *TInfo,
6305 FunctionDecl::StorageClass SC,
6306 bool &IsVirtualOkay) {
6307 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6308 DeclarationName Name = NameInfo.getName();
6309
6310 FunctionDecl *NewFD = 0;
6311 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006312
David Blaikiebbafb8a2012-03-11 07:00:24 +00006313 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006314 // Determine whether the function was written with a
6315 // prototype. This true when:
6316 // - there is a prototype in the declarator, or
6317 // - the type R of the function is some kind of typedef or other reference
6318 // to a type name (which eventually refers to a function type).
6319 bool HasPrototype =
6320 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6321 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6322
David Blaikie30d15442011-10-19 22:56:21 +00006323 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006324 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006325 TInfo, SC, isInline,
6326 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006327 if (D.isInvalidType())
6328 NewFD->setInvalidDecl();
6329
6330 // Set the lexical context.
6331 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6332
6333 return NewFD;
6334 }
6335
6336 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6337 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6338
6339 // Check that the return type is not an abstract class type.
6340 // For record types, this is done by the AbstractClassUsageDiagnoser once
6341 // the class has been completely parsed.
6342 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006343 SemaRef.RequireNonAbstractType(
6344 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6345 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006346 D.setInvalidType();
6347
6348 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6349 // This is a C++ constructor declaration.
6350 assert(DC->isRecord() &&
6351 "Constructors can only be declared in a member context");
6352
6353 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6354 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006355 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006356 R, TInfo, isExplicit, isInline,
6357 /*isImplicitlyDeclared=*/false,
6358 isConstexpr);
6359
6360 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6361 // This is a C++ destructor declaration.
6362 if (DC->isRecord()) {
6363 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6364 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6365 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6366 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006367 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006368 NameInfo, R, TInfo, isInline,
6369 /*isImplicitlyDeclared=*/false);
6370
6371 // If the class is complete, then we now create the implicit exception
6372 // specification. If the class is incomplete or dependent, we can't do
6373 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006374 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006375 Record->getDefinition() && !Record->isBeingDefined() &&
6376 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6377 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6378 }
6379
6380 IsVirtualOkay = true;
6381 return NewDD;
6382
6383 } else {
6384 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6385 D.setInvalidType();
6386
6387 // Create a FunctionDecl to satisfy the function definition parsing
6388 // code path.
6389 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006390 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006391 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006392 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006393 /*hasPrototype=*/true, isConstexpr);
6394 }
6395
6396 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6397 if (!DC->isRecord()) {
6398 SemaRef.Diag(D.getIdentifierLoc(),
6399 diag::err_conv_function_not_member);
6400 return 0;
6401 }
6402
6403 SemaRef.CheckConversionDeclarator(D, R, SC);
6404 IsVirtualOkay = true;
6405 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006406 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006407 R, TInfo, isInline, isExplicit,
6408 isConstexpr, SourceLocation());
6409
6410 } else if (DC->isRecord()) {
6411 // If the name of the function is the same as the name of the record,
6412 // then this must be an invalid constructor that has a return type.
6413 // (The parser checks for a return type and makes the declarator a
6414 // constructor if it has no return type).
6415 if (Name.getAsIdentifierInfo() &&
6416 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6417 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6418 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6419 << SourceRange(D.getIdentifierLoc());
6420 return 0;
6421 }
6422
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006423 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006424 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6425 cast<CXXRecordDecl>(DC),
6426 D.getLocStart(), NameInfo, R,
6427 TInfo, SC, isInline,
6428 isConstexpr, SourceLocation());
6429 IsVirtualOkay = !Ret->isStatic();
6430 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006431 } else {
6432 // Determine whether the function was written with a
6433 // prototype. This true when:
6434 // - we're in C++ (where every function has a prototype),
6435 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006436 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006437 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006438 true/*HasPrototype*/, isConstexpr);
6439 }
6440}
6441
Matt Arsenaultefb38192013-07-23 01:23:36 +00006442enum OpenCLParamType {
6443 ValidKernelParam,
6444 PtrPtrKernelParam,
6445 PtrKernelParam,
David Tweedababa8f2014-03-27 16:34:11 +00006446 PrivatePtrKernelParam,
Matt Arsenaultefb38192013-07-23 01:23:36 +00006447 InvalidKernelParam,
6448 RecordKernelParam
6449};
6450
6451static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6452 if (PT->isPointerType()) {
6453 QualType PointeeType = PT->getPointeeType();
David Tweedababa8f2014-03-27 16:34:11 +00006454 if (PointeeType->isPointerType())
6455 return PtrPtrKernelParam;
6456 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6457 : PtrKernelParam;
Matt Arsenaultefb38192013-07-23 01:23:36 +00006458 }
6459
6460 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6461 // be used as builtin types.
6462
6463 if (PT->isImageType())
6464 return PtrKernelParam;
6465
6466 if (PT->isBooleanType())
6467 return InvalidKernelParam;
6468
6469 if (PT->isEventT())
6470 return InvalidKernelParam;
6471
6472 if (PT->isHalfType())
6473 return InvalidKernelParam;
6474
6475 if (PT->isRecordType())
6476 return RecordKernelParam;
6477
6478 return ValidKernelParam;
6479}
6480
6481static void checkIsValidOpenCLKernelParameter(
6482 Sema &S,
6483 Declarator &D,
6484 ParmVarDecl *Param,
6485 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6486 QualType PT = Param->getType();
6487
6488 // Cache the valid types we encounter to avoid rechecking structs that are
6489 // used again
6490 if (ValidTypes.count(PT.getTypePtr()))
6491 return;
6492
6493 switch (getOpenCLKernelParameterType(PT)) {
6494 case PtrPtrKernelParam:
6495 // OpenCL v1.2 s6.9.a:
6496 // A kernel function argument cannot be declared as a
6497 // pointer to a pointer type.
6498 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6499 D.setInvalidType();
6500 return;
6501
David Tweedababa8f2014-03-27 16:34:11 +00006502 case PrivatePtrKernelParam:
6503 // OpenCL v1.2 s6.9.a:
6504 // A kernel function argument cannot be declared as a
6505 // pointer to the private address space.
6506 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6507 D.setInvalidType();
6508 return;
6509
Matt Arsenaultefb38192013-07-23 01:23:36 +00006510 // OpenCL v1.2 s6.9.k:
6511 // Arguments to kernel functions in a program cannot be declared with the
6512 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6513 // uintptr_t or a struct and/or union that contain fields declared to be
6514 // one of these built-in scalar types.
6515
6516 case InvalidKernelParam:
6517 // OpenCL v1.2 s6.8 n:
6518 // A kernel function argument cannot be declared
6519 // of event_t type.
6520 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6521 D.setInvalidType();
6522 return;
6523
6524 case PtrKernelParam:
6525 case ValidKernelParam:
6526 ValidTypes.insert(PT.getTypePtr());
6527 return;
6528
6529 case RecordKernelParam:
6530 break;
6531 }
6532
6533 // Track nested structs we will inspect
6534 SmallVector<const Decl *, 4> VisitStack;
6535
6536 // Track where we are in the nested structs. Items will migrate from
6537 // VisitStack to HistoryStack as we do the DFS for bad field.
6538 SmallVector<const FieldDecl *, 4> HistoryStack;
6539 HistoryStack.push_back((const FieldDecl *) 0);
6540
6541 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6542 VisitStack.push_back(PD);
6543
6544 assert(VisitStack.back() && "First decl null?");
6545
6546 do {
6547 const Decl *Next = VisitStack.pop_back_val();
6548 if (!Next) {
6549 assert(!HistoryStack.empty());
6550 // Found a marker, we have gone up a level
6551 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6552 ValidTypes.insert(Hist->getType().getTypePtr());
6553
6554 continue;
6555 }
6556
6557 // Adds everything except the original parameter declaration (which is not a
6558 // field itself) to the history stack.
6559 const RecordDecl *RD;
6560 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6561 HistoryStack.push_back(Field);
6562 RD = Field->getType()->castAs<RecordType>()->getDecl();
6563 } else {
6564 RD = cast<RecordDecl>(Next);
6565 }
6566
6567 // Add a null marker so we know when we've gone back up a level
6568 VisitStack.push_back((const Decl *) 0);
6569
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006570 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006571 QualType QT = FD->getType();
6572
6573 if (ValidTypes.count(QT.getTypePtr()))
6574 continue;
6575
6576 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6577 if (ParamType == ValidKernelParam)
6578 continue;
6579
6580 if (ParamType == RecordKernelParam) {
6581 VisitStack.push_back(FD);
6582 continue;
6583 }
6584
6585 // OpenCL v1.2 s6.9.p:
6586 // Arguments to kernel functions that are declared to be a struct or union
6587 // do not allow OpenCL objects to be passed as elements of the struct or
6588 // union.
David Tweedababa8f2014-03-27 16:34:11 +00006589 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6590 ParamType == PrivatePtrKernelParam) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006591 S.Diag(Param->getLocation(),
6592 diag::err_record_with_pointers_kernel_param)
6593 << PT->isUnionType()
6594 << PT;
6595 } else {
6596 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6597 }
6598
6599 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6600 << PD->getDeclName();
6601
6602 // We have an error, now let's go back up through history and show where
6603 // the offending field came from
6604 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6605 E = HistoryStack.end(); I != E; ++I) {
6606 const FieldDecl *OuterField = *I;
6607 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6608 << OuterField->getType();
6609 }
6610
6611 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6612 << QT->isPointerType()
6613 << QT;
6614 D.setInvalidType();
6615 return;
6616 }
6617 } while (!VisitStack.empty());
6618}
6619
Mike Stump11289f42009-09-09 15:08:12 +00006620NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006621Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006622 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006623 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006624 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006625 QualType R = TInfo->getType();
6626
Zhongxing Xubece5d62009-01-16 01:13:29 +00006627 assert(R.getTypePtr()->isFunctionType());
6628
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006629 // TODO: consider using NameInfo for diagnostic.
6630 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6631 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006632 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006633
Richard Smithb4a9e862013-04-12 22:46:28 +00006634 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6635 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6636 diag::err_invalid_thread)
6637 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006638
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006639 if (D.isFirstDeclarationOfMember())
6640 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006641
Douglas Gregor513e63c2010-12-10 19:28:19 +00006642 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006643 FunctionTemplateDecl *FunctionTemplate = 0;
6644 bool isExplicitSpecialization = false;
6645 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006646
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006647 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006648 bool HasExplicitTemplateArgs = false;
6649 TemplateArgumentListInfo TemplateArgs;
6650
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006651 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006652
Richard Smith541b38b2013-09-20 01:15:31 +00006653 DeclContext *OriginalDC = DC;
6654 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6655
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006656 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6657 isVirtualOkay);
6658 if (!NewFD) return 0;
6659
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006660 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6661 NewFD->setTopLevelDeclInObjCContainer();
6662
Richard Smith541b38b2013-09-20 01:15:31 +00006663 // Set the lexical context. If this is a function-scope declaration, or has a
6664 // C++ scope specifier, or is the object of a friend declaration, the lexical
6665 // context will be different from the semantic context.
6666 NewFD->setLexicalDeclContext(CurContext);
6667
6668 if (IsLocalExternDecl)
6669 NewFD->setLocalExternDecl();
6670
David Blaikiebbafb8a2012-03-11 07:00:24 +00006671 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006672 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006673 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6674 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006675 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006676 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006677 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006678 // C++ [class.friend]p5
6679 // A function can be defined in a friend declaration of a
6680 // class . . . . Such a function is implicitly inline.
6681 NewFD->setImplicitlyInline();
6682 }
6683
John McCalldb632ac2012-09-25 07:32:39 +00006684 // If this is a method defined in an __interface, and is not a constructor
6685 // or an overloaded operator, then set the pure flag (isVirtual will already
6686 // return true).
6687 if (const CXXRecordDecl *Parent =
6688 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6689 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006690 NewFD->setPure(true);
6691 }
6692
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006693 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006694 isExplicitSpecialization = false;
6695 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006696 if (D.isInvalidType())
6697 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006698
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006699 // Match up the template parameter lists with the scope specifier, then
6700 // determine whether we have a template or a template specialization.
6701 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006702 if (TemplateParameterList *TemplateParams =
6703 MatchTemplateParametersToScopeSpecifier(
6704 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00006705 D.getCXXScopeSpec(),
6706 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6707 ? D.getName().TemplateId
6708 : 0,
6709 TemplateParamLists, isFriend, isExplicitSpecialization,
6710 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006711 if (TemplateParams->size() > 0) {
6712 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006713
Abramo Bagnara60804e12011-03-18 15:16:37 +00006714 // Check that we can declare a template here.
6715 if (CheckTemplateDeclScope(S, TemplateParams))
6716 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006717
Abramo Bagnara60804e12011-03-18 15:16:37 +00006718 // A destructor cannot be a template.
6719 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6720 Diag(NewFD->getLocation(), diag::err_destructor_template);
6721 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006722 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006723
6724 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006725 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006726 // now that we know what the current instantiation is.
6727 if (DC->isDependentContext()) {
6728 ContextRAII SavedContext(*this, DC);
6729 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6730 Invalid = true;
6731 }
6732
John McCall1f0479e2010-03-24 08:27:58 +00006733
Abramo Bagnara60804e12011-03-18 15:16:37 +00006734 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6735 NewFD->getLocation(),
6736 Name, TemplateParams,
6737 NewFD);
6738 FunctionTemplate->setLexicalDeclContext(CurContext);
6739 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6740
6741 // For source fidelity, store the other template param lists.
6742 if (TemplateParamLists.size() > 1) {
6743 NewFD->setTemplateParameterListsInfo(Context,
6744 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006745 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006746 }
6747 } else {
6748 // This is a function template specialization.
6749 isFunctionTemplateSpecialization = true;
6750 // For source fidelity, store all the template param lists.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006751 if (TemplateParamLists.size() > 0)
6752 NewFD->setTemplateParameterListsInfo(Context,
6753 TemplateParamLists.size(),
6754 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006755
6756 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6757 if (isFriend) {
6758 // We want to remove the "template<>", found here.
6759 SourceRange RemoveRange = TemplateParams->getSourceRange();
6760
6761 // If we remove the template<> and the name is not a
6762 // template-id, we're actually silently creating a problem:
6763 // the friend declaration will refer to an untemplated decl,
6764 // and clearly the user wants a template specialization. So
6765 // we need to insert '<>' after the name.
6766 SourceLocation InsertLoc;
6767 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6768 InsertLoc = D.getName().getSourceRange().getEnd();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006769 InsertLoc = getLocForEndOfToken(InsertLoc);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006770 }
6771
6772 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6773 << Name << RemoveRange
6774 << FixItHint::CreateRemoval(RemoveRange)
6775 << FixItHint::CreateInsertion(InsertLoc, "<>");
6776 }
6777 }
6778 }
6779 else {
6780 // All template param lists were matched against the scope specifier:
6781 // this is NOT (an explicit specialization of) a template.
6782 if (TemplateParamLists.size() > 0)
6783 // For source fidelity, store all the template param lists.
6784 NewFD->setTemplateParameterListsInfo(Context,
6785 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006786 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006787 }
6788
6789 if (Invalid) {
6790 NewFD->setInvalidDecl();
6791 if (FunctionTemplate)
6792 FunctionTemplate->setInvalidDecl();
6793 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006794
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006795 // C++ [dcl.fct.spec]p5:
6796 // The virtual specifier shall only be used in declarations of
6797 // nonstatic class member functions that appear within a
6798 // member-specification of a class declaration; see 10.3.
6799 //
6800 if (isVirtual && !NewFD->isInvalidDecl()) {
6801 if (!isVirtualOkay) {
6802 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6803 diag::err_virtual_non_function);
6804 } else if (!CurContext->isRecord()) {
6805 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006806 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6807 diag::err_virtual_out_of_class)
6808 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6809 } else if (NewFD->getDescribedFunctionTemplate()) {
6810 // C++ [temp.mem]p3:
6811 // A member function template shall not be virtual.
6812 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6813 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006814 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6815 } else {
6816 // Okay: Add virtual to the method.
6817 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006818 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006819
6820 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006821 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006822 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006823 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006824
Richard Smithc1564702013-11-15 02:58:23 +00006825 if (getLangOpts().CPlusPlus1y &&
6826 (NewFD->isDependentContext() ||
6827 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006828 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006829 // If the function template is referenced directly (for instance, as a
6830 // member of the current instantiation), pretend it has a dependent type.
6831 // This is not really justified by the standard, but is the only sane
6832 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006833 // FIXME: For a friend function, we have not marked the function as being
6834 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006835 const FunctionProtoType *FPT =
6836 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006837 QualType Result =
6838 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006839 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006840 FPT->getExtProtoInfo()));
6841 }
6842
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006843 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006844 // The inline specifier shall not appear on a block scope function
6845 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006846 if (isInline && !NewFD->isInvalidDecl()) {
6847 if (CurContext->isFunctionOrMethod()) {
6848 // 'inline' is not allowed on block scope function declaration.
6849 Diag(D.getDeclSpec().getInlineSpecLoc(),
6850 diag::err_inline_declaration_block_scope) << Name
6851 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6852 }
6853 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006854
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006855 // C++ [dcl.fct.spec]p6:
6856 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006857 // constructor or conversion function within its class definition;
6858 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006859 if (isExplicit && !NewFD->isInvalidDecl()) {
6860 if (!CurContext->isRecord()) {
6861 // 'explicit' was specified outside of the class.
6862 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6863 diag::err_explicit_out_of_class)
6864 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6865 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6866 !isa<CXXConversionDecl>(NewFD)) {
6867 // 'explicit' was specified on a function that wasn't a constructor
6868 // or conversion function.
6869 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6870 diag::err_explicit_non_ctor_or_conv_function)
6871 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6872 }
6873 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006874
Richard Smitha77a0a62011-08-15 21:04:07 +00006875 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006876 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006877 // are implicitly inline.
6878 NewFD->setImplicitlyInline();
6879
Richard Smith574f4f62013-01-14 05:37:29 +00006880 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006881 // be either constructors or to return a literal type. Therefore,
6882 // destructors cannot be declared constexpr.
6883 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006884 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006885 }
6886
Douglas Gregor26701a42011-09-09 02:06:17 +00006887 // If __module_private__ was specified, mark the function accordingly.
6888 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006889 if (isFunctionTemplateSpecialization) {
6890 SourceLocation ModulePrivateLoc
6891 = D.getDeclSpec().getModulePrivateSpecLoc();
6892 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6893 << 0
6894 << FixItHint::CreateRemoval(ModulePrivateLoc);
6895 } else {
6896 NewFD->setModulePrivate();
6897 if (FunctionTemplate)
6898 FunctionTemplate->setModulePrivate();
6899 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006900 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006901
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006902 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006903 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006904 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006905 FunctionTemplate->setAccess(AS_public);
6906 }
Richard Smith64017682013-07-17 23:53:16 +00006907 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006908 NewFD->setAccess(AS_public);
6909 }
6910
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006911 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006912 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6913 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006914 switch (D.getFunctionDefinitionKind()) {
6915 case FDK_Declaration:
6916 case FDK_Definition:
6917 break;
6918
6919 case FDK_Defaulted:
6920 NewFD->setDefaulted();
6921 break;
6922
6923 case FDK_Deleted:
6924 NewFD->setDeletedAsWritten();
6925 break;
6926 }
6927
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006928 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6929 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006930 // C++ [class.mfct]p2:
6931 // A member function may be defined (8.4) in its class definition, in
6932 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006933 NewFD->setImplicitlyInline();
6934 }
6935
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006936 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6937 !CurContext->isRecord()) {
6938 // C++ [class.static]p1:
6939 // A data or function member of a class may be declared static
6940 // in a class definition, in which case it is a static member of
6941 // the class.
6942
6943 // Complain about the 'static' specifier if it's on an out-of-line
6944 // member function definition.
6945 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6946 diag::err_static_out_of_line)
6947 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6948 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006949
6950 // C++11 [except.spec]p15:
6951 // A deallocation function with no exception-specification is treated
6952 // as if it were specified with noexcept(true).
6953 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6954 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6955 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006956 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006957 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6958 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00006959 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006960 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006961 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006962 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006963
6964 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006965 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006966 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006967 isExplicitSpecialization ||
6968 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006969
Zhongxing Xubece5d62009-01-16 01:13:29 +00006970 // Handle GNU asm-label extension (encoded as an attribute).
6971 if (Expr *E = (Expr*) D.getAsmLabel()) {
6972 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006973 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006974 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006975 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006976 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6977 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6978 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6979 if (I != ExtnameUndeclaredIdentifiers.end()) {
6980 NewFD->addAttr(I->second);
6981 ExtnameUndeclaredIdentifiers.erase(I);
6982 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006983 }
6984
Chris Lattner9af40c12009-04-25 06:12:16 +00006985 // Copy the parameter declarations from the declarator D to the function
6986 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006987 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006988 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006989 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006990
Zhongxing Xubece5d62009-01-16 01:13:29 +00006991 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6992 // function that takes no arguments, not a function that takes a
6993 // single void argument.
6994 // We let through "const void" here because Sema::GetTypeForDeclarator
6995 // already checks for that case.
Alp Toker4284c6e2014-05-11 16:05:55 +00006996 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
Alp Tokerc5350722014-02-26 22:27:52 +00006997 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
6998 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006999 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7000 Param->setDeclContext(NewFD);
7001 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00007002
7003 if (Param->isInvalidDecl())
7004 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007005 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007006 }
Mike Stump11289f42009-09-09 15:08:12 +00007007
John McCall9dd450b2009-09-21 23:43:11 +00007008 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00007009 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00007010 // following example, we'll need to synthesize (unnamed)
7011 // parameters for use in the declaration.
7012 //
7013 // @code
7014 // typedef void fn(int);
7015 // fn f;
7016 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00007017
Chris Lattner47c0d002009-04-25 06:03:53 +00007018 // Synthesize a parameter for each argument type.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007019 for (const auto &AI : FT->param_types()) {
John McCalla3ccba02010-06-04 11:21:44 +00007020 ParmVarDecl *Param =
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007021 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00007022 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00007023 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00007024 }
Chris Lattner49303b22009-04-25 18:38:18 +00007025 } else {
7026 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7027 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00007028 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00007029
Chris Lattner9af40c12009-04-25 06:12:16 +00007030 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00007031 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00007032
James Molloy6f8780b2012-02-29 10:24:19 +00007033 // Find all anonymous symbols defined during the declaration of this function
7034 // and add to NewFD. This lets us track decls such 'enum Y' in:
7035 //
7036 // void f(enum Y {AA} x) {}
7037 //
7038 // which would otherwise incorrectly end up in the translation unit scope.
7039 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7040 DeclsInPrototypeScope.clear();
7041
Richard Smithdebc59d2013-01-30 05:45:05 +00007042 if (D.getDeclSpec().isNoreturnSpecified())
7043 NewFD->addAttr(
7044 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00007045 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00007046
Richard Smith84208dc2012-03-13 05:56:40 +00007047 // Functions returning a variably modified type violate C99 6.7.5.2p2
7048 // because all functions have linkage.
7049 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00007050 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00007051 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7052 NewFD->setInvalidDecl();
7053 }
7054
Warren Huntc3b18962014-04-08 22:30:47 +00007055 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7056 !NewFD->hasAttr<SectionAttr>()) {
7057 NewFD->addAttr(
7058 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7059 CodeSegStack.CurrentValue->getString(),
7060 CodeSegStack.CurrentPragmaLocation));
7061 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7062 PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7063 NewFD->dropAttr<SectionAttr>();
7064 }
7065
Rafael Espindolac67f2232012-05-10 02:50:16 +00007066 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00007067 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00007068
Alp Toker314cc812014-01-25 16:55:45 +00007069 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007070 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7071 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7072 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7073 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007074 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
David Blaikie080a61c2014-02-09 07:24:41 +00007075 // Attach WarnUnusedResult to functions returning types with that attribute.
7076 // Don't apply the attribute to that type's own non-static member functions
7077 // (to avoid warning on things like assignment operators)
7078 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00007079 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007080 }
7081
Joey Gouly16cb99d2014-01-06 11:26:18 +00007082 if (getLangOpts().OpenCL) {
7083 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7084 // type declaration will generate a compilation error.
7085 unsigned AddressSpace = RetType.getAddressSpace();
7086 if (AddressSpace == LangAS::opencl_local ||
7087 AddressSpace == LangAS::opencl_global ||
7088 AddressSpace == LangAS::opencl_constant) {
7089 Diag(NewFD->getLocation(),
7090 diag::err_opencl_return_value_with_address_space);
7091 NewFD->setInvalidDecl();
7092 }
7093 }
7094
David Blaikiebbafb8a2012-03-11 07:00:24 +00007095 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007096 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007097 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007098 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7099 CheckMain(NewFD, D.getDeclSpec());
7100
David Majnemerc729b0b2013-09-16 22:44:20 +00007101 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7102 CheckMSVCRTEntryPoint(NewFD);
7103
David Majnemer027f9c42013-07-06 02:13:46 +00007104 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007105 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7106 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007107 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007108 // Make graceful recovery from an invalid redeclaration.
7109 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007110 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007111 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7112 "previous declaration set still overloaded");
7113 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007114 // C++11 [replacement.functions]p3:
7115 // The program's definitions shall not be specified as inline.
7116 //
7117 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7118 //
7119 // Suppress the diagnostic if the function is __attribute__((used)), since
7120 // that forces an external definition to be emitted.
7121 if (D.getDeclSpec().isInlineSpecified() &&
7122 NewFD->isReplaceableGlobalAllocationFunction() &&
7123 !NewFD->hasAttr<UsedAttr>())
7124 Diag(D.getDeclSpec().getInlineSpecLoc(),
7125 diag::ext_operator_new_delete_declared_inline)
7126 << NewFD->getDeclName();
7127
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007128 // If the declarator is a template-id, translate the parser's template
7129 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007130 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7131 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7132 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7133 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007134 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007135 TemplateId->NumArgs);
7136 translateTemplateArguments(TemplateArgsPtr,
7137 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007138
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007139 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007140
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007141 if (NewFD->isInvalidDecl()) {
7142 HasExplicitTemplateArgs = false;
7143 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007144 // Function template with explicit template arguments.
7145 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7146 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7147
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007148 HasExplicitTemplateArgs = false;
John McCallf7cfb222010-10-13 05:45:15 +00007149 } else {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007150 assert((isFunctionTemplateSpecialization ||
7151 D.getDeclSpec().isFriendSpecified()) &&
7152 "should have a 'template<>' for this decl");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007153 // "friend void foo<>(int);" is an implicit specialization decl.
7154 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007155 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007156 } else if (isFriend && isFunctionTemplateSpecialization) {
7157 // This combination is only possible in a recovery case; the user
7158 // wrote something like:
7159 // template <> friend void foo(int);
7160 // which we're recovering from as if the user had written:
7161 // friend void foo<>(int);
7162 // Go ahead and fake up a template id.
7163 HasExplicitTemplateArgs = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00007164 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007165 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007166 }
John McCallf7cfb222010-10-13 05:45:15 +00007167
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007168 // If it's a friend (and only if it's a friend), it's possible
7169 // that either the specialized function type or the specialized
7170 // template is dependent, and therefore matching will fail. In
7171 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007172 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007173 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007174 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7175 TemplateSpecializationType::anyDependentTemplateArguments(
7176 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7177 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007178 assert(HasExplicitTemplateArgs &&
7179 "friend function specialization without template args");
7180 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7181 Previous))
7182 NewFD->setInvalidDecl();
7183 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007184 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007185 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007186 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007187 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007188 diag::ext_function_specialization_in_class :
7189 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007190 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007191 } else if (CheckFunctionTemplateSpecialization(NewFD,
7192 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7193 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007194 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007195
7196 // C++ [dcl.stc]p1:
7197 // A storage-class-specifier shall not be specified in an explicit
7198 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007199 FunctionTemplateSpecializationInfo *Info =
7200 NewFD->getTemplateSpecializationInfo();
7201 if (Info && SC != SC_None) {
7202 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007203 Diag(NewFD->getLocation(),
7204 diag::err_explicit_specialization_inconsistent_storage_class)
7205 << SC
7206 << FixItHint::CreateRemoval(
7207 D.getDeclSpec().getStorageClassSpecLoc());
7208
7209 else
7210 Diag(NewFD->getLocation(),
7211 diag::ext_explicit_specialization_storage_class)
7212 << FixItHint::CreateRemoval(
7213 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007214 }
7215
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007216 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7217 if (CheckMemberSpecialization(NewFD, Previous))
7218 NewFD->setInvalidDecl();
7219 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007220
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007221 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007222 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007223 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7224 CheckMain(NewFD, D.getDeclSpec());
7225
David Majnemerc729b0b2013-09-16 22:44:20 +00007226 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7227 CheckMSVCRTEntryPoint(NewFD);
7228
Nico Weber7607fce2013-12-21 00:49:51 +00007229 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007230 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7231 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007232 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007233
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007234 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007235 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7236 "previous declaration set still overloaded");
7237
7238 NamedDecl *PrincipalDecl = (FunctionTemplate
7239 ? cast<NamedDecl>(FunctionTemplate)
7240 : NewFD);
7241
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007242 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007243 AccessSpecifier Access = AS_public;
7244 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007245 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007246
7247 NewFD->setAccess(Access);
7248 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007249 }
7250
7251 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7252 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7253 PrincipalDecl->setNonMemberOperator();
7254
7255 // If we have a function template, check the template parameter
7256 // list. This will check and merge default template arguments.
7257 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007258 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007259 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007260 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007261 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007262 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007263 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007264 ? TPC_FriendFunctionTemplateDefinition
7265 : TPC_FriendFunctionTemplate)
7266 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007267 DC && DC->isRecord() &&
7268 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007269 ? TPC_ClassTemplateMember
7270 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007271 }
7272
7273 if (NewFD->isInvalidDecl()) {
7274 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007275 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007276 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007277 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007278 // Fake up an access specifier if it's supposed to be a class member.
7279 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7280 NewFD->setAccess(AS_public);
7281
7282 // Qualified decls generally require a previous declaration.
7283 if (D.getCXXScopeSpec().isSet()) {
7284 // ...with the major exception of templated-scope or
7285 // dependent-scope friend declarations.
7286
7287 // TODO: we currently also suppress this check in dependent
7288 // contexts because (1) the parameter depth will be off when
7289 // matching friend templates and (2) we might actually be
7290 // selecting a friend based on a dependent factor. But there
7291 // are situations where these conditions don't apply and we
7292 // can actually do this check immediately.
7293 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007294 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007295 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7296 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007297 // ignore these
7298 } else {
7299 // The user tried to provide an out-of-line definition for a
7300 // function that is a member of a class or namespace, but there
7301 // was no such member function declared (C++ [class.mfct]p2,
7302 // C++ [namespace.memdef]p2). For example:
7303 //
7304 // class X {
7305 // void f() const;
7306 // };
7307 //
7308 // void X::f() { } // ill-formed
7309 //
7310 // Complain about this problem, and attempt to suggest close
7311 // matches (e.g., those that differ only in cv-qualifiers and
7312 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007313
Richard Smith114394f2013-08-09 04:35:01 +00007314 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7315 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007316 AddToScope = ExtraArgs.AddToScope;
7317 return Result;
7318 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007319 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007320
7321 // Unqualified local friend declarations are required to resolve
7322 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007323 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007324 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7325 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007326 AddToScope = ExtraArgs.AddToScope;
7327 return Result;
7328 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007329 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007330
Richard Smitha2302242013-12-05 07:51:02 +00007331 } else if (!D.isFunctionDefinition() &&
7332 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007333 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007334 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007335 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007336 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007337 // Note that this is not the case for explicit specializations of
7338 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007339 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7340 // extension for compatibility with old SWIG code which likes to
7341 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007342 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7343 << D.getCXXScopeSpec().getRange();
7344 }
7345 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007346
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007347 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007348 checkAttributesAfterMerging(*this, *NewFD);
7349
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007350 AddKnownFunctionAttributes(NewFD);
7351
Douglas Gregor72609052010-08-06 13:50:58 +00007352 if (NewFD->hasAttr<OverloadableAttr>() &&
7353 !NewFD->getType()->getAs<FunctionProtoType>()) {
7354 Diag(NewFD->getLocation(),
7355 diag::err_attribute_overloadable_no_prototype)
7356 << NewFD;
7357
7358 // Turn this into a variadic function with no parameters.
7359 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007360 FunctionProtoType::ExtProtoInfo EPI(
7361 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007362 EPI.Variadic = true;
7363 EPI.ExtInfo = FT->getExtInfo();
7364
Alp Toker314cc812014-01-25 16:55:45 +00007365 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007366 NewFD->setType(R);
7367 }
7368
Eli Friedman570024a2010-08-05 06:57:20 +00007369 // If there's a #pragma GCC visibility in scope, and this isn't a class
7370 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007371 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007372 AddPushedVisibilityAttribute(NewFD);
7373
John McCall32f5fe12011-09-30 05:12:12 +00007374 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7375 // marking the function.
7376 AddCFAuditedAttribute(NewFD);
7377
Richard Smithac974a32013-06-30 09:48:50 +00007378 // If this is the first declaration of an extern C variable, update
7379 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007380 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007381 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007382 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007383
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007384 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007385 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007386
Nico Rieck82f0b062014-03-31 14:56:15 +00007387 if (D.isRedeclaration() && !Previous.empty()) {
7388 checkDLLAttributeRedeclaration(
7389 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7390 isExplicitSpecialization || isFunctionTemplateSpecialization);
7391 }
7392
David Blaikiebbafb8a2012-03-11 07:00:24 +00007393 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007394 if (FunctionTemplate) {
7395 if (NewFD->isInvalidDecl())
7396 FunctionTemplate->setInvalidDecl();
7397 return FunctionTemplate;
7398 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007399 }
Mike Stump11289f42009-09-09 15:08:12 +00007400
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007401 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007402 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7403 if ((getLangOpts().OpenCLVersion >= 120)
7404 && (SC == SC_Static)) {
7405 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7406 D.setInvalidType();
7407 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007408
7409 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007410 if (!NewFD->getReturnType()->isVoidType()) {
Tanya Lattner0f864332013-01-30 19:48:52 +00007411 Diag(D.getIdentifierLoc(),
7412 diag::err_expected_kernel_void_return_type);
7413 D.setInvalidType();
7414 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007415
7416 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007417 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007418 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007419 }
7420
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007421 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007422
David Blaikiebbafb8a2012-03-11 07:00:24 +00007423 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007424 if (IdentifierInfo *II = NewFD->getIdentifier())
7425 if (!NewFD->isInvalidDecl() &&
7426 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7427 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007428 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007429 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7430
7431 Context.setcudaConfigureCallDecl(NewFD);
7432 }
7433 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007434
7435 // Here we have an function template explicit specialization at class scope.
7436 // The actually specialization will be postponed to template instatiation
7437 // time via the ClassScopeFunctionSpecializationDecl node.
7438 if (isDependentClassScopeExplicitSpecialization) {
7439 ClassScopeFunctionSpecializationDecl *NewSpec =
7440 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007441 Context, CurContext, SourceLocation(),
7442 cast<CXXMethodDecl>(NewFD),
7443 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007444 CurContext->addDecl(NewSpec);
7445 AddToScope = false;
7446 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007447
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007448 return NewFD;
7449}
7450
7451/// \brief Perform semantic checking of a new function declaration.
7452///
7453/// Performs semantic analysis of the new function declaration
7454/// NewFD. This routine performs all semantic checking that does not
7455/// require the actual declarator involved in the declaration, and is
7456/// used both for the declaration of functions as they are parsed
7457/// (called via ActOnDeclarator) and for the declaration of functions
7458/// that have been instantiated via C++ template instantiation (called
7459/// via InstantiateDecl).
7460///
James Dennettffad8b72012-06-22 08:10:18 +00007461/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007462/// an explicit specialization of the previous declaration.
7463///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007464/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007465///
James Dennettffad8b72012-06-22 08:10:18 +00007466/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007467bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007468 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007469 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007470 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7471 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007472
Richard Smith1c34fb72013-08-13 18:18:50 +00007473 // Determine whether the type of this function should be merged with
7474 // a previous visible declaration. This never happens for functions in C++,
7475 // and always happens in C if the previous declaration was visible.
7476 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7477 !Previous.isShadowed();
7478
Douglas Gregor3552dab2013-01-09 00:47:56 +00007479 // Filter out any non-conflicting previous declarations.
7480 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7481
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007482 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007483 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007484
Douglas Gregore62c0a42009-02-24 01:23:02 +00007485 // Merge or overload the declaration with an existing declaration of
7486 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007487 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007488 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007489 // a declaration that requires merging. If it's an overload,
7490 // there's no more work to do here; we'll just add the new
7491 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007492 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007493 NamedDecl *Candidate = Previous.getFoundDecl();
7494 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7495 Redeclaration = true;
7496 OldDecl = Candidate;
7497 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007498 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007499 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7500 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007501 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007502 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007503 break;
7504
7505 case Ovl_NonFunction:
7506 Redeclaration = true;
7507 break;
7508
7509 case Ovl_Overload:
7510 Redeclaration = false;
7511 break;
John McCall1f82f242009-11-18 22:49:29 +00007512 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007513
David Blaikiebbafb8a2012-03-11 07:00:24 +00007514 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007515 // If a function name is overloadable in C, then every function
7516 // with that name must be marked "overloadable".
7517 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7518 << Redeclaration << NewFD;
7519 NamedDecl *OverloadedDecl = 0;
7520 if (Redeclaration)
7521 OverloadedDecl = OldDecl;
7522 else if (!Previous.empty())
7523 OverloadedDecl = Previous.getRepresentativeDecl();
7524 if (OverloadedDecl)
7525 Diag(OverloadedDecl->getLocation(),
7526 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007527 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007528 }
John McCall1f82f242009-11-18 22:49:29 +00007529 }
Richard Smith574f4f62013-01-14 05:37:29 +00007530 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007531
Richard Smithac974a32013-06-30 09:48:50 +00007532 // Check for a previous extern "C" declaration with this name.
7533 if (!Redeclaration &&
7534 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7535 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7536 if (!Previous.empty()) {
7537 // This is an extern "C" declaration with the same name as a previous
7538 // declaration, and thus redeclares that entity...
7539 Redeclaration = true;
7540 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007541 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007542
7543 // ... except in the presence of __attribute__((overloadable)).
7544 if (OldDecl->hasAttr<OverloadableAttr>()) {
7545 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7546 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7547 << Redeclaration << NewFD;
7548 Diag(Previous.getFoundDecl()->getLocation(),
7549 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007550 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007551 }
7552 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7553 Redeclaration = false;
7554 OldDecl = 0;
7555 }
7556 }
7557 }
7558 }
7559
Richard Smith574f4f62013-01-14 05:37:29 +00007560 // C++11 [dcl.constexpr]p8:
7561 // A constexpr specifier for a non-static member function that is not
7562 // a constructor declares that member function to be const.
7563 //
7564 // This needs to be delayed until we know whether this is an out-of-line
7565 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007566 //
7567 // This rule is not present in C++1y, so we produce a backwards
7568 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007569 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007570 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7571 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007572 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Alp Tokera2794f92014-01-22 07:29:52 +00007573 CXXMethodDecl *OldMD = 0;
7574 if (OldDecl)
7575 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007576 if (!OldMD || !OldMD->isStatic()) {
7577 const FunctionProtoType *FPT =
7578 MD->getType()->castAs<FunctionProtoType>();
7579 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7580 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007581 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007582 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007583
7584 // Warn that we did this, if we're not performing template instantiation.
7585 // In that case, we'll have warned already when the template was defined.
7586 if (ActiveTemplateInstantiations.empty()) {
7587 SourceLocation AddConstLoc;
7588 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7589 .IgnoreParens().getAs<FunctionTypeLoc>())
Alp Tokerb6cc5922014-05-03 03:45:55 +00007590 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
Richard Smith034185c2013-04-21 01:08:50 +00007591
7592 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7593 << FixItHint::CreateInsertion(AddConstLoc, " const");
7594 }
Richard Smith574f4f62013-01-14 05:37:29 +00007595 }
7596 }
7597
7598 if (Redeclaration) {
7599 // NewFD and OldDecl represent declarations that need to be
7600 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007601 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007602 NewFD->setInvalidDecl();
7603 return Redeclaration;
7604 }
7605
7606 Previous.clear();
7607 Previous.addDecl(OldDecl);
7608
7609 if (FunctionTemplateDecl *OldTemplateDecl
7610 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7611 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7612 FunctionTemplateDecl *NewTemplateDecl
7613 = NewFD->getDescribedFunctionTemplate();
7614 assert(NewTemplateDecl && "Template/non-template mismatch");
7615 if (CXXMethodDecl *Method
7616 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7617 Method->setAccess(OldTemplateDecl->getAccess());
7618 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007619 }
Richard Smith574f4f62013-01-14 05:37:29 +00007620
7621 // If this is an explicit specialization of a member that is a function
7622 // template, mark it as a member specialization.
7623 if (IsExplicitSpecialization &&
7624 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7625 NewTemplateDecl->setMemberSpecialization();
7626 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007627 }
Richard Smith574f4f62013-01-14 05:37:29 +00007628
7629 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007630 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007631 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007632
7633 if (isa<CXXMethodDecl>(NewFD)) {
7634 // A valid redeclaration of a C++ method must be out-of-line,
7635 // but (unfortunately) it's not necessarily a definition
7636 // because of templates, which means that the previous
7637 // declaration is not necessarily from the class definition.
7638
7639 // For just setting the access, that doesn't matter.
7640 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7641 NewFD->setAccess(oldMethod->getAccess());
7642
7643 // Update the key-function state if necessary for this ABI.
7644 if (NewFD->isInlined() &&
7645 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7646 // setNonKeyFunction needs to work with the original
7647 // declaration from the class definition, and isVirtual() is
7648 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007649 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007650 if (oldMethod->isVirtual()) {
7651 Context.setNonKeyFunction(oldMethod);
7652 }
7653 }
7654 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007655 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007656 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007657
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007658 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007659 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007660 // C++-specific checks.
7661 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7662 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007663 } else if (CXXDestructorDecl *Destructor =
7664 dyn_cast<CXXDestructorDecl>(NewFD)) {
7665 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007666 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007667
Douglas Gregor7454c562010-07-02 20:37:36 +00007668 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007669 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007670 if (!ClassType->isDependentType()) {
7671 DeclarationName Name
7672 = Context.DeclarationNames.getCXXDestructorName(
7673 Context.getCanonicalType(ClassType));
7674 if (NewFD->getDeclName() != Name) {
7675 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007676 NewFD->setInvalidDecl();
7677 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007678 }
7679 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007680 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007681 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007682 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007683 }
7684
7685 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7687 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007688 !Method->getDescribedFunctionTemplate() &&
7689 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007690 if (AddOverriddenMethods(Method->getParent(), Method)) {
7691 // If the function was marked as "static", we have a problem.
7692 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007693 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007694 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007695 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007696 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007697
7698 if (Method->isStatic())
7699 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007700 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007701
7702 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7703 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007704 CheckOverloadedOperatorDeclaration(NewFD)) {
7705 NewFD->setInvalidDecl();
7706 return Redeclaration;
7707 }
Alexis Huntc88db062010-01-13 09:01:02 +00007708
7709 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7710 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007711 CheckLiteralOperatorDeclaration(NewFD)) {
7712 NewFD->setInvalidDecl();
7713 return Redeclaration;
7714 }
Alexis Huntc88db062010-01-13 09:01:02 +00007715
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007716 // In C++, check default arguments now that we have merged decls. Unless
7717 // the lexical context is the class, because in this case this is done
7718 // during delayed parsing anyway.
7719 if (!CurContext->isRecord())
7720 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007721
Douglas Gregor9246b682010-12-21 19:47:46 +00007722 // If this function declares a builtin function, check the type of this
7723 // declaration against the expected type for the builtin.
7724 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7725 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007726 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007727 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7728 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7729 // The type of this function differs from the type of the builtin,
7730 // so forget about the builtin entirely.
7731 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7732 }
7733 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007734
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007735 // If this function is declared as being extern "C", then check to see if
7736 // the function returns a UDT (class, struct, or union type) that is not C
7737 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007738 // But, issue any diagnostic on the first declaration only.
7739 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007740 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007741 if (R->isIncompleteType() && !R->isVoidType())
7742 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7743 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007744 else if (!R.isPODType(Context) && !R->isVoidType() &&
7745 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007746 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007747 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007748 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007749 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007750}
7751
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007752static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7753 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7754 if (!TSI)
7755 return SourceRange();
7756
7757 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007758 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007759 if (!FunctionTL)
7760 return SourceRange();
7761
Alp Toker42a16a62014-01-25 23:51:36 +00007762 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007763 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007764 return ResultTL.getSourceRange();
7765
7766 return SourceRange();
7767}
7768
David Blaikied937bf12011-09-08 06:33:04 +00007769void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007770 // C++11 [basic.start.main]p3:
7771 // A program that [...] declares main to be inline, static or
7772 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007773 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7774 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007775 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007776 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007777 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007778 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007779 ? diag::err_static_main : diag::warn_static_main)
7780 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7781 if (FD->isInlineSpecified())
7782 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7783 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007784 if (DS.isNoreturnSpecified()) {
7785 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007786 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007787 Diag(NoreturnLoc, diag::ext_noreturn_main);
7788 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7789 << FixItHint::CreateRemoval(NoreturnRange);
7790 }
Richard Smith3f333f22012-02-04 06:10:17 +00007791 if (FD->isConstexpr()) {
7792 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7793 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7794 FD->setConstexpr(false);
7795 }
John McCall02dee0a2009-07-25 04:36:53 +00007796
Joey Goulya7310a82013-11-05 12:30:39 +00007797 if (getLangOpts().OpenCL) {
7798 Diag(FD->getLocation(), diag::err_opencl_no_main)
7799 << FD->hasAttr<OpenCLKernelAttr>();
7800 FD->setInvalidDecl();
7801 return;
7802 }
7803
John McCall02dee0a2009-07-25 04:36:53 +00007804 QualType T = FD->getType();
7805 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007806 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007807
John McCall5ed3caf2012-02-14 19:50:52 +00007808 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007809 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007810 // In C and C++, main magically returns 0 if you fall off the end;
7811 // set the flag which tells us that.
7812 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7813 FD->setHasImplicitReturnZero(true);
7814
7815 // In C with GNU extensions we allow main() to have non-integer return
7816 // type, but we should warn about the extension, and we disable the
7817 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007818 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007819 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7820
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007821 SourceRange ResultRange = getResultSourceRange(FD);
7822 if (ResultRange.isValid())
7823 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7824 << FixItHint::CreateReplacement(ResultRange, "int");
7825
John McCall5ed3caf2012-02-14 19:50:52 +00007826 // Otherwise, this is just a flat-out error.
7827 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007828 SourceRange ResultRange = getResultSourceRange(FD);
7829 if (ResultRange.isValid())
7830 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7831 << FixItHint::CreateReplacement(ResultRange, "int");
7832 else
7833 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7834
John McCall02dee0a2009-07-25 04:36:53 +00007835 FD->setInvalidDecl(true);
7836 }
7837
7838 // Treat protoless main() as nullary.
7839 if (isa<FunctionNoProtoType>(FT)) return;
7840
7841 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007842 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007843 assert(FD->getNumParams() == nparams);
7844
John McCall0e21fcc2009-12-24 09:58:38 +00007845 bool HasExtraParameters = (nparams > 3);
7846
7847 // Darwin passes an undocumented fourth argument of type char**. If
7848 // other platforms start sprouting these, the logic below will start
7849 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007850 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007851 HasExtraParameters = false;
7852
7853 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007854 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7855 FD->setInvalidDecl(true);
7856 nparams = 3;
7857 }
7858
7859 // FIXME: a lot of the following diagnostics would be improved
7860 // if we had some location information about types.
7861
7862 QualType CharPP =
7863 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007864 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007865
7866 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007867 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007868
7869 bool mismatch = true;
7870
7871 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7872 mismatch = false;
7873 else if (Expected[i] == CharPP) {
7874 // As an extension, the following forms are okay:
7875 // char const **
7876 // char const * const *
7877 // char * const *
7878
John McCall8ccfcb52009-09-24 19:53:00 +00007879 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007880 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007881 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7882 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007883 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7884 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007885 qs.removeConst();
7886 mismatch = !qs.empty();
7887 }
7888 }
7889
7890 if (mismatch) {
7891 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7892 // TODO: suggest replacing given type with expected type
7893 FD->setInvalidDecl(true);
7894 }
7895 }
7896
7897 if (nparams == 1 && !FD->isInvalidDecl()) {
7898 Diag(FD->getLocation(), diag::warn_main_one_arg);
7899 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007900
7901 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007902 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007903 FD->setInvalidDecl();
7904 }
7905}
7906
7907void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7908 QualType T = FD->getType();
7909 assert(T->isFunctionType() && "function decl is not of function type");
7910 const FunctionType *FT = T->castAs<FunctionType>();
7911
7912 // Set an implicit return of 'zero' if the function can return some integral,
7913 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007914 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7915 FT->getReturnType()->isAnyPointerType() ||
7916 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007917 // DllMain is exempt because a return value of zero means it failed.
7918 if (FD->getName() != "DllMain")
7919 FD->setHasImplicitReturnZero(true);
7920
7921 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007922 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007923 FD->setInvalidDecl();
7924 }
John McCalld9baf6a2009-07-24 03:03:21 +00007925}
7926
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007927bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007928 // FIXME: Need strict checking. In C89, we need to check for
7929 // any assignment, increment, decrement, function-calls, or
7930 // commas outside of a sizeof. In C99, it's the same list,
7931 // except that the aforementioned are allowed in unevaluated
7932 // expressions. Everything else falls under the
7933 // "may accept other forms of constant expressions" exception.
7934 // (We never end up here for C++, so the constant expression
7935 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007936 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007937 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007938 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7939 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007940 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007941}
7942
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007943namespace {
7944 // Visits an initialization expression to see if OrigDecl is evaluated in
7945 // its own initialization and throws a warning if it does.
7946 class SelfReferenceChecker
7947 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7948 Sema &S;
7949 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007950 bool isRecordType;
7951 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007952 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007953
7954 public:
7955 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7956
7957 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007958 S(S), OrigDecl(OrigDecl) {
7959 isPODType = false;
7960 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007961 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007962 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7963 isPODType = VD->getType().isPODType(S.Context);
7964 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007965 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007966 }
7967 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007968
Richard Trieu64c51ab2012-05-09 00:21:34 +00007969 // For most expressions, the cast is directly above the DeclRefExpr.
7970 // For conditional operators, the cast can be outside the conditional
7971 // operator if both expressions are DeclRefExpr's.
7972 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007973 if (isReferenceType)
7974 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007975 E = E->IgnoreParenImpCasts();
7976 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7977 HandleDeclRefExpr(DRE);
7978 return;
7979 }
7980
7981 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7982 HandleValue(CO->getTrueExpr());
7983 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007984 return;
7985 }
7986
7987 if (isa<MemberExpr>(E)) {
7988 Expr *Base = E->IgnoreParenImpCasts();
7989 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7990 // Check for static member variables and don't warn on them.
7991 if (!isa<FieldDecl>(ME->getMemberDecl()))
7992 return;
7993 Base = ME->getBase()->IgnoreParenImpCasts();
7994 }
7995 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7996 HandleDeclRefExpr(DRE);
7997 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007998 }
7999 }
8000
Richard Trieu32673472012-10-01 17:39:51 +00008001 // Reference types are handled here since all uses of references are
8002 // bad, not just r-value uses.
8003 void VisitDeclRefExpr(DeclRefExpr *E) {
8004 if (isReferenceType)
8005 HandleDeclRefExpr(E);
8006 }
8007
Richard Trieu64c51ab2012-05-09 00:21:34 +00008008 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00008009 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00008010 (isRecordType && E->getCastKind() == CK_NoOp))
8011 HandleValue(E->getSubExpr());
8012
8013 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008014 }
8015
Richard Trieua04ad1a2011-09-01 21:44:13 +00008016 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00008017 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00008018 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008019
Richard Trieu742c6ed2012-10-03 00:41:36 +00008020 // Warn when a non-static method call is followed by non-static member
8021 // field accesses, which is followed by a DeclRefExpr.
8022 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8023 bool Warn = (MD && !MD->isStatic());
8024 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8025 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8026 if (!isa<FieldDecl>(ME->getMemberDecl()))
8027 Warn = false;
8028 Base = ME->getBase()->IgnoreParenImpCasts();
8029 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008030
Richard Trieu742c6ed2012-10-03 00:41:36 +00008031 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8032 if (Warn)
8033 HandleDeclRefExpr(DRE);
8034 return;
8035 }
8036
8037 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8038 // Visit that expression.
8039 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008040 }
8041
Richard Trieu8fbd91d2013-03-26 03:41:40 +00008042 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8043 if (E->getNumArgs() > 0)
8044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8045 HandleDeclRefExpr(DRE);
8046
8047 Inherited::VisitCXXOperatorCallExpr(E);
8048 }
8049
Richard Trieua04ad1a2011-09-01 21:44:13 +00008050 void VisitUnaryOperator(UnaryOperator *E) {
8051 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00008052 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8053 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8054 if (!isPODType)
8055 HandleValue(E->getSubExpr());
8056 return;
8057 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008058 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00008059 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008060
8061 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8062
Richard Trieua04ad1a2011-09-01 21:44:13 +00008063 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00008064 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008065 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00008066 unsigned diag;
8067 if (isReferenceType) {
8068 diag = diag::warn_uninit_self_reference_in_reference_init;
8069 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8070 diag = diag::warn_static_self_reference_in_init;
8071 } else {
8072 diag = diag::warn_uninit_self_reference_in_init;
8073 }
8074
Richard Trieua04ad1a2011-09-01 21:44:13 +00008075 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00008076 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00008077 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008078 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00008079 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008080 }
8081 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008082
Richard Trieu32673472012-10-01 17:39:51 +00008083 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8084 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8085 bool DirectInit) {
8086 // Parameters arguments are occassionially constructed with itself,
8087 // for instance, in recursive functions. Skip them.
8088 if (isa<ParmVarDecl>(OrigDecl))
8089 return;
8090
8091 E = E->IgnoreParens();
8092
8093 // Skip checking T a = a where T is not a record or reference type.
8094 // Doing so is a way to silence uninitialized warnings.
8095 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8096 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8097 if (ICE->getCastKind() == CK_LValueToRValue)
8098 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8099 if (DRE->getDecl() == OrigDecl)
8100 return;
8101
8102 SelfReferenceChecker(S, OrigDecl).Visit(E);
8103 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008104}
8105
Douglas Gregor5fb53972009-01-14 15:45:31 +00008106/// AddInitializerToDecl - Adds the initializer Init to the
8107/// declaration dcl. If DirectInit is true, this is C++ direct
8108/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008109void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8110 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008111 // If there is no declaration, there was an error parsing it. Just ignore
8112 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008113 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008114 return;
Mike Stump11289f42009-09-09 15:08:12 +00008115
Douglas Gregor0c880302009-03-11 23:00:04 +00008116 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8117 // With declarators parsed the way they are, the parser cannot
8118 // distinguish between a normal initializer and a pure-specifier.
8119 // Thus this grotesque test.
8120 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008121 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008122 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8123 CheckPureMethod(Method, Init->getSourceRange());
8124 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008125 Diag(Method->getLocation(), diag::err_member_function_initialization)
8126 << Method->getDeclName() << Init->getSourceRange();
8127 Method->setInvalidDecl();
8128 }
8129 return;
8130 }
8131
Steve Naroff437b4d82007-09-12 20:13:48 +00008132 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8133 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008134 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8135 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008136 RealDecl->setInvalidDecl();
8137 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008138 }
Sebastian Redla9351792012-02-11 23:51:47 +00008139 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8140
Richard Smith0cc85782011-12-15 19:20:59 +00008141 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008142 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008143 Expr *DeduceInit = Init;
8144 // Initializer could be a C++ direct-initializer. Deduction only works if it
8145 // contains exactly one expression.
8146 if (CXXDirectInit) {
8147 if (CXXDirectInit->getNumExprs() == 0) {
8148 // It isn't possible to write this directly, but it is possible to
8149 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008150 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008151 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8152 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008153 << VDecl->getDeclName() << VDecl->getType()
8154 << VDecl->getSourceRange();
8155 RealDecl->setInvalidDecl();
8156 return;
8157 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008158 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008159 VDecl->isInitCapture()
8160 ? diag::err_init_capture_multiple_expressions
8161 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008162 << VDecl->getDeclName() << VDecl->getType()
8163 << VDecl->getSourceRange();
8164 RealDecl->setInvalidDecl();
8165 return;
8166 } else {
8167 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008168 if (isa<InitListExpr>(DeduceInit))
8169 Diag(CXXDirectInit->getLocStart(),
8170 diag::err_auto_var_init_paren_braces)
8171 << VDecl->getDeclName() << VDecl->getType()
8172 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008173 }
8174 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008175
8176 // Expressions default to 'id' when we're in a debugger.
8177 bool DefaultedToAuto = false;
8178 if (getLangOpts().DebuggerCastResultToId &&
8179 Init->getType() == Context.UnknownAnyTy) {
8180 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8181 if (Result.isInvalid()) {
8182 VDecl->setInvalidDecl();
8183 return;
8184 }
8185 Init = Result.take();
8186 DefaultedToAuto = true;
8187 }
Richard Smith061f1e22013-04-30 21:23:01 +00008188
8189 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008190 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008191 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008192 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008193 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008194 RealDecl->setInvalidDecl();
8195 return;
8196 }
Richard Smith061f1e22013-04-30 21:23:01 +00008197 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008198 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008199
John McCall31168b02011-06-15 23:02:42 +00008200 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008201 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008202 VDecl->setInvalidDecl();
8203
Jordan Rosed8d56692012-06-08 22:46:07 +00008204 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8205 // 'id' instead of a specific object type prevents most of our usual checks.
8206 // We only want to warn outside of template instantiations, though:
8207 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008208 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008209 DeducedType->isObjCIdType()) {
8210 SourceLocation Loc =
8211 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008212 Diag(Loc, diag::warn_auto_var_is_id)
8213 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8214 }
8215
Richard Smith30482bc2011-02-20 03:19:35 +00008216 // If this is a redeclaration, check that the type we just deduced matches
8217 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008218 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8219 // We never need to merge the type, because we cannot form an incomplete
8220 // array of auto, nor deduce such a type.
8221 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8222 }
Richard Smith27d807c2013-04-30 13:56:41 +00008223
8224 // Check the deduced type is valid for a variable declaration.
8225 CheckVariableDeclarationType(VDecl);
8226 if (VDecl->isInvalidDecl())
8227 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008228 }
Richard Smith0cc85782011-12-15 19:20:59 +00008229
Nico Rieck8e9791f2014-02-26 21:27:13 +00008230 // dllimport cannot be used on variable definitions.
8231 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8232 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8233 VDecl->setInvalidDecl();
8234 return;
8235 }
8236
Richard Smith0cc85782011-12-15 19:20:59 +00008237 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8238 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8239 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8240 VDecl->setInvalidDecl();
8241 return;
8242 }
8243
Sebastian Redla9351792012-02-11 23:51:47 +00008244 if (!VDecl->getType()->isDependentType()) {
8245 // A definition must end up with a complete type, which means it must be
8246 // complete with the restriction that an array type might be completed by
8247 // the initializer; note that later code assumes this restriction.
8248 QualType BaseDeclType = VDecl->getType();
8249 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8250 BaseDeclType = Array->getElementType();
8251 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8252 diag::err_typecheck_decl_incomplete_type)) {
8253 RealDecl->setInvalidDecl();
8254 return;
8255 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008256
Sebastian Redla9351792012-02-11 23:51:47 +00008257 // The variable can not have an abstract class type.
8258 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8259 diag::err_abstract_type_in_decl,
8260 AbstractVariableType))
8261 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008262 }
8263
Sebastian Redl5ca79842010-02-01 20:16:42 +00008264 const VarDecl *Def;
8265 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008266 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008267 << VDecl->getDeclName();
8268 Diag(Def->getLocation(), diag::note_previous_definition);
8269 VDecl->setInvalidDecl();
8270 return;
8271 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008272
Douglas Gregorf0f83692010-08-24 05:27:49 +00008273 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008274 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008275 // C++ [class.static.data]p4
8276 // If a static data member is of const integral or const
8277 // enumeration type, its declaration in the class definition can
8278 // specify a constant-initializer which shall be an integral
8279 // constant expression (5.19). In that case, the member can appear
8280 // in integral constant expressions. The member shall still be
8281 // defined in a namespace scope if it is used in the program and the
8282 // namespace scope definition shall not contain an initializer.
8283 //
8284 // We already performed a redefinition check above, but for static
8285 // data members we also need to check whether there was an in-class
8286 // declaration with an initializer.
8287 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008288 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8289 << VDecl->getDeclName();
8290 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008291 return;
8292 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008293
Douglas Gregor71f39c92010-12-16 01:31:22 +00008294 if (VDecl->hasLocalStorage())
8295 getCurFunction()->setHasBranchProtectedScope();
8296
8297 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8298 VDecl->setInvalidDecl();
8299 return;
8300 }
8301 }
John McCalld4e1b762010-08-01 01:24:59 +00008302
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008303 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8304 // a kernel function cannot be initialized."
8305 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8306 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8307 VDecl->setInvalidDecl();
8308 return;
8309 }
8310
Steve Naroff61091402007-09-12 14:07:44 +00008311 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008312 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008313 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008314
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008315 // Expressions default to 'id' when we're in a debugger
8316 // and we are assigning it to a variable of Objective-C pointer type.
8317 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8318 Init->getType() == Context.UnknownAnyTy) {
8319 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8320 if (Result.isInvalid()) {
8321 VDecl->setInvalidDecl();
8322 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008323 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008324 Init = Result.take();
8325 }
Richard Smith0cc85782011-12-15 19:20:59 +00008326
8327 // Perform the initialization.
8328 if (!VDecl->isInvalidDecl()) {
8329 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8330 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008331 = DirectInit ?
8332 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8333 Init->getLocStart(),
8334 Init->getLocEnd())
8335 : InitializationKind::CreateDirectList(
8336 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008337 : InitializationKind::CreateCopy(VDecl->getLocation(),
8338 Init->getLocStart());
8339
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008340 MultiExprArg Args = Init;
8341 if (CXXDirectInit)
8342 Args = MultiExprArg(CXXDirectInit->getExprs(),
8343 CXXDirectInit->getNumExprs());
8344
8345 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8346 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008347 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008348 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008349 return;
Steve Naroff61091402007-09-12 14:07:44 +00008350 }
Richard Smith0cc85782011-12-15 19:20:59 +00008351
8352 Init = Result.takeAs<Expr>();
8353 }
8354
Richard Trieu32673472012-10-01 17:39:51 +00008355 // Check for self-references within variable initializers.
8356 // Variables declared within a function/method body (except for references)
8357 // are handled by a dataflow analysis.
8358 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8359 VDecl->getType()->isReferenceType()) {
8360 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8361 }
8362
Richard Smith0cc85782011-12-15 19:20:59 +00008363 // If the type changed, it means we had an incomplete type that was
8364 // completed by the initializer. For example:
8365 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008366 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008367 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008368 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008369
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008370 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008371 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8372
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008373 if (VDecl->hasAttr<BlocksAttr>())
8374 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008375
8376 // It is safe to assign a weak reference into a strong variable.
8377 // Although this code can still have problems:
8378 // id x = self.weakProp;
8379 // id y = self.weakProp;
8380 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8381 // paths through the function. This should be revisited if
8382 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008383 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008384 DiagnosticsEngine::Level Level =
8385 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8386 Init->getLocStart());
8387 if (Level != DiagnosticsEngine::Ignored)
8388 getCurFunction()->markSafeWeakUse(Init);
8389 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008390 }
8391
Richard Smith945f8d32013-01-14 22:39:08 +00008392 // The initialization is usually a full-expression.
8393 //
8394 // FIXME: If this is a braced initialization of an aggregate, it is not
8395 // an expression, and each individual field initializer is a separate
8396 // full-expression. For instance, in:
8397 //
8398 // struct Temp { ~Temp(); };
8399 // struct S { S(Temp); };
8400 // struct T { S a, b; } t = { Temp(), Temp() }
8401 //
8402 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008403 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8404 false,
8405 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008406 if (Result.isInvalid()) {
8407 VDecl->setInvalidDecl();
8408 return;
8409 }
8410 Init = Result.take();
8411
Richard Smith0cc85782011-12-15 19:20:59 +00008412 // Attach the initializer to the decl.
8413 VDecl->setInit(Init);
8414
8415 if (VDecl->isLocalVarDecl()) {
8416 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8417 // static storage duration shall be constant expressions or string literals.
8418 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008419 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8420 if (VDecl->getStorageClass() == SC_Static)
8421 CheckForConstantInitializer(Init, DclT);
8422 // C89 is stricter than C99 for non-static aggregate types.
8423 // C89 6.5.7p3: All the expressions [...] in an initializer list
8424 // for an object that has aggregate or union type shall be
8425 // constant expressions.
8426 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008427 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008428 !Init->isConstantInitializer(Context, false))
8429 Diag(Init->getExprLoc(),
8430 diag::ext_aggregate_init_not_constant)
8431 << Init->getSourceRange();
8432 }
Mike Stump11289f42009-09-09 15:08:12 +00008433 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008434 VDecl->getLexicalDeclContext()->isRecord()) {
8435 // This is an in-class initialization for a static data member, e.g.,
8436 //
8437 // struct S {
8438 // static const int value = 17;
8439 // };
8440
Douglas Gregor0c880302009-03-11 23:00:04 +00008441 // C++ [class.mem]p4:
8442 // A member-declarator can contain a constant-initializer only
8443 // if it declares a static member (9.4) of const integral or
8444 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008445 //
Richard Smith0cc85782011-12-15 19:20:59 +00008446 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008447 // If a non-volatile const static data member is of integral or
8448 // enumeration type, its declaration in the class definition can
8449 // specify a brace-or-equal-initializer in which every initalizer-clause
8450 // that is an assignment-expression is a constant expression. A static
8451 // data member of literal type can be declared in the class definition
8452 // with the constexpr specifier; if so, its declaration shall specify a
8453 // brace-or-equal-initializer in which every initializer-clause that is
8454 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008455
8456 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008457 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008458
Richard Smith2316cd82011-09-29 19:11:37 +00008459 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008460 // type. We separately check that every constexpr variable is of literal
8461 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008462 } else if (VDecl->isConstexpr()) {
8463
John McCalldb768922010-09-10 23:21:22 +00008464 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008465 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008466 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8467 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008468 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008469
8470 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008471 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008472 // Check whether the expression is a constant expression.
8473 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008474 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008475 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008476 // in-class initializer cannot be volatile.
8477 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8478 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008479 ; // Nothing to check.
8480 else if (Init->isIntegerConstantExpr(Context, &Loc))
8481 ; // Ok, it's an ICE!
8482 else if (Init->isEvaluatable(Context)) {
8483 // If we can constant fold the initializer through heroics, accept it,
8484 // but report this as a use of an extension for -pedantic.
8485 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8486 << Init->getSourceRange();
8487 } else {
8488 // Otherwise, this is some crazy unknown case. Report the issue at the
8489 // location provided by the isIntegerConstantExpr failed check.
8490 Diag(Loc, diag::err_in_class_initializer_non_constant)
8491 << Init->getSourceRange();
8492 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008493 }
8494
Richard Smith0cc85782011-12-15 19:20:59 +00008495 // We allow foldable floating-point constants as an extension.
8496 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008497 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8498 // it anyway and provide a fixit to add the 'constexpr'.
8499 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008500 Diag(VDecl->getLocation(),
8501 diag::ext_in_class_initializer_float_type_cxx11)
8502 << DclT << Init->getSourceRange();
8503 Diag(VDecl->getLocStart(),
8504 diag::note_in_class_initializer_float_type_cxx11)
8505 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008506 } else {
8507 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8508 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008509
Richard Smithcf656382013-01-25 04:22:16 +00008510 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8511 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8512 << Init->getSourceRange();
8513 VDecl->setInvalidDecl();
8514 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008515 }
Richard Smith256336d2011-09-29 23:18:34 +00008516
Richard Smith0cc85782011-12-15 19:20:59 +00008517 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008518 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008519 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008520 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008521 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8522 VDecl->setConstexpr(true);
8523
Richard Smith2316cd82011-09-29 19:11:37 +00008524 } else {
8525 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008526 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008527 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008528 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008529 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008530 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008531 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008532 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008533 VDecl->isExternC())) &&
8534 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008535 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008536
Richard Smith0cc85782011-12-15 19:20:59 +00008537 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008538 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008539 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00008540 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008541
Sebastian Redla9351792012-02-11 23:51:47 +00008542 // We will represent direct-initialization similarly to copy-initialization:
8543 // int x(1); -as-> int x = 1;
8544 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8545 //
8546 // Clients that want to distinguish between the two forms, can check for
8547 // direct initializer using VarDecl::getInitStyle().
8548 // A major benefit is that clients that don't particularly care about which
8549 // exactly form was it (like the CodeGen) can handle both cases without
8550 // special case code.
8551
8552 // C++ 8.5p11:
8553 // The form of initialization (using parentheses or '=') is generally
8554 // insignificant, but does matter when the entity being initialized has a
8555 // class type.
8556 if (CXXDirectInit) {
8557 assert(DirectInit && "Call-style initializer must be direct init.");
8558 VDecl->setInitStyle(VarDecl::CallInit);
8559 } else if (DirectInit) {
8560 // This must be list-initialization. No other way is direct-initialization.
8561 VDecl->setInitStyle(VarDecl::ListInit);
8562 }
8563
John McCall8b7fd8f12011-01-19 11:48:09 +00008564 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008565}
8566
John McCalleae5acb2010-03-31 02:13:20 +00008567/// ActOnInitializerError - Given that there was an error parsing an
8568/// initializer for the given declaration, try to return to some form
8569/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008570void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008571 // Our main concern here is re-establishing invariants like "a
8572 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008573 if (!D || D->isInvalidDecl()) return;
8574
8575 VarDecl *VD = dyn_cast<VarDecl>(D);
8576 if (!VD) return;
8577
Richard Smith30482bc2011-02-20 03:19:35 +00008578 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008579 if (ParsingInitForAutoVars.count(D)) {
8580 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008581 return;
8582 }
8583
John McCalleae5acb2010-03-31 02:13:20 +00008584 QualType Ty = VD->getType();
8585 if (Ty->isDependentType()) return;
8586
8587 // Require a complete type.
8588 if (RequireCompleteType(VD->getLocation(),
8589 Context.getBaseElementType(Ty),
8590 diag::err_typecheck_decl_incomplete_type)) {
8591 VD->setInvalidDecl();
8592 return;
8593 }
8594
Alp Toker48c7e172014-04-15 16:24:50 +00008595 // Require a non-abstract type.
John McCalleae5acb2010-03-31 02:13:20 +00008596 if (RequireNonAbstractType(VD->getLocation(), Ty,
8597 diag::err_abstract_type_in_decl,
8598 AbstractVariableType)) {
8599 VD->setInvalidDecl();
8600 return;
8601 }
8602
8603 // Don't bother complaining about constructors or destructors,
8604 // though.
8605}
8606
John McCall48871652010-08-21 09:40:31 +00008607void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008608 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008609 // If there is no declaration, there was an error parsing it. Just ignore it.
8610 if (RealDecl == 0)
8611 return;
8612
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008613 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8614 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008615
Richard Smithf0215fe2011-12-25 21:17:58 +00008616 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008617 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008618 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8619 << Var->getDeclName() << Type;
8620 Var->setInvalidDecl();
8621 return;
8622 }
Mike Stump11289f42009-09-09 15:08:12 +00008623
Richard Smithf0215fe2011-12-25 21:17:58 +00008624 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008625 // the constexpr specifier; if so, its declaration shall specify
8626 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008627 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8628 // the definition of a variable [...] or the declaration of a static data
8629 // member.
8630 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8631 if (Var->isStaticDataMember())
8632 Diag(Var->getLocation(),
8633 diag::err_constexpr_static_mem_var_requires_init)
8634 << Var->getDeclName();
8635 else
8636 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008637 Var->setInvalidDecl();
8638 return;
8639 }
8640
Joey Gouly96b94e62014-01-03 14:16:55 +00008641 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8642 // be initialized.
8643 if (!Var->isInvalidDecl() &&
8644 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008645 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008646 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8647 Var->setInvalidDecl();
8648 return;
8649 }
8650
Douglas Gregore6565622010-02-09 07:26:29 +00008651 switch (Var->isThisDeclarationADefinition()) {
8652 case VarDecl::Definition:
8653 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8654 break;
8655
8656 // We have an out-of-line definition of a static data member
8657 // that has an in-class initializer, so we type-check this like
8658 // a declaration.
8659 //
8660 // Fall through
8661
8662 case VarDecl::DeclarationOnly:
8663 // It's only a declaration.
8664
8665 // Block scope. C99 6.7p7: If an identifier for an object is
8666 // declared with no linkage (C99 6.2.2p6), the type for the
8667 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008668 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008669 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008670 RequireCompleteType(Var->getLocation(), Type,
8671 diag::err_typecheck_decl_incomplete_type))
8672 Var->setInvalidDecl();
8673
8674 // Make sure that the type is not abstract.
8675 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8676 RequireNonAbstractType(Var->getLocation(), Type,
8677 diag::err_abstract_type_in_decl,
8678 AbstractVariableType))
8679 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008680 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008681 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008682 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008683 Diag(Var->getLocation(), diag::note_private_extern);
8684 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008685
Douglas Gregore6565622010-02-09 07:26:29 +00008686 return;
8687
8688 case VarDecl::TentativeDefinition:
8689 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8690 // object that has file scope without an initializer, and without a
8691 // storage-class specifier or with the storage-class specifier "static",
8692 // constitutes a tentative definition. Note: A tentative definition with
8693 // external linkage is valid (C99 6.2.2p5).
8694 if (!Var->isInvalidDecl()) {
8695 if (const IncompleteArrayType *ArrayT
8696 = Context.getAsIncompleteArrayType(Type)) {
8697 if (RequireCompleteType(Var->getLocation(),
8698 ArrayT->getElementType(),
8699 diag::err_illegal_decl_array_incomplete_type))
8700 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008701 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008702 // C99 6.9.2p3: If the declaration of an identifier for an object is
8703 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8704 // declared type shall not be an incomplete type.
8705 // NOTE: code such as the following
8706 // static struct s;
8707 // struct s { int a; };
8708 // is accepted by gcc. Hence here we issue a warning instead of
8709 // an error and we do not invalidate the static declaration.
8710 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008711 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008712 RequireCompleteType(Var->getLocation(), Type,
8713 diag::ext_typecheck_decl_incomplete_type);
8714 }
8715 }
8716
8717 // Record the tentative definition; we're done.
8718 if (!Var->isInvalidDecl())
8719 TentativeDefinitions.push_back(Var);
8720 return;
8721 }
8722
8723 // Provide a specific diagnostic for uninitialized variable
8724 // definitions with incomplete array type.
8725 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008726 Diag(Var->getLocation(),
8727 diag::err_typecheck_incomplete_array_needs_initializer);
8728 Var->setInvalidDecl();
8729 return;
8730 }
8731
John McCalla755f0f2010-08-01 01:25:24 +00008732 // Provide a specific diagnostic for uninitialized variable
8733 // definitions with reference type.
8734 if (Type->isReferenceType()) {
8735 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8736 << Var->getDeclName()
8737 << SourceRange(Var->getLocation(), Var->getLocation());
8738 Var->setInvalidDecl();
8739 return;
8740 }
Douglas Gregore6565622010-02-09 07:26:29 +00008741
8742 // Do not attempt to type-check the default initializer for a
8743 // variable with dependent type.
8744 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008745 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008746
Douglas Gregore6565622010-02-09 07:26:29 +00008747 if (Var->isInvalidDecl())
8748 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008749
Douglas Gregore6565622010-02-09 07:26:29 +00008750 if (RequireCompleteType(Var->getLocation(),
8751 Context.getBaseElementType(Type),
8752 diag::err_typecheck_decl_incomplete_type)) {
8753 Var->setInvalidDecl();
8754 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008755 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008756
Douglas Gregore6565622010-02-09 07:26:29 +00008757 // The variable can not have an abstract class type.
8758 if (RequireNonAbstractType(Var->getLocation(), Type,
8759 diag::err_abstract_type_in_decl,
8760 AbstractVariableType)) {
8761 Var->setInvalidDecl();
8762 return;
8763 }
8764
Douglas Gregor9574af62011-05-21 17:52:48 +00008765 // Check for jumps past the implicit initializer. C++0x
8766 // clarifies that this applies to a "variable with automatic
8767 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008768 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008769 // A program that jumps from a point where a variable with automatic
8770 // storage duration is not in scope to a point where it is in scope is
8771 // ill-formed unless the variable has scalar type, class type with a
8772 // trivial default constructor and a trivial destructor, a cv-qualified
8773 // version of one of these types, or an array of one of the preceding
8774 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008775 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008776 if (const RecordType *Record
8777 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008778 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008779 // Mark the function for further checking even if the looser rules of
8780 // C++11 do not require such checks, so that we can diagnose
8781 // incompatibilities with C++98.
8782 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008783 getCurFunction()->setHasBranchProtectedScope();
8784 }
Douglas Gregore6565622010-02-09 07:26:29 +00008785 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008786
8787 // C++03 [dcl.init]p9:
8788 // If no initializer is specified for an object, and the
8789 // object is of (possibly cv-qualified) non-POD class type (or
8790 // array thereof), the object shall be default-initialized; if
8791 // the object is of const-qualified type, the underlying class
8792 // type shall have a user-declared default
8793 // constructor. Otherwise, if no initializer is specified for
8794 // a non- static object, the object and its subobjects, if
8795 // any, have an indeterminate initial value); if the object
8796 // or any of its subobjects are of const-qualified type, the
8797 // program is ill-formed.
8798 // C++0x [dcl.init]p11:
8799 // If no initializer is specified for an object, the object is
8800 // default-initialized; [...].
8801 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8802 InitializationKind Kind
8803 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008804
8805 InitializationSequence InitSeq(*this, Entity, Kind, None);
8806 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008807 if (Init.isInvalid())
8808 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008809 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008810 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008811 // This is important for template substitution.
8812 Var->setInitStyle(VarDecl::CallInit);
8813 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008814
John McCall8b7fd8f12011-01-19 11:48:09 +00008815 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008816 }
8817}
8818
Richard Smith02e85f32011-04-14 22:09:26 +00008819void Sema::ActOnCXXForRangeDecl(Decl *D) {
8820 VarDecl *VD = dyn_cast<VarDecl>(D);
8821 if (!VD) {
8822 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8823 D->setInvalidDecl();
8824 return;
8825 }
8826
8827 VD->setCXXForRangeDecl(true);
8828
8829 // for-range-declaration cannot be given a storage class specifier.
8830 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008831 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008832 case SC_None:
8833 break;
8834 case SC_Extern:
8835 Error = 0;
8836 break;
8837 case SC_Static:
8838 Error = 1;
8839 break;
8840 case SC_PrivateExtern:
8841 Error = 2;
8842 break;
8843 case SC_Auto:
8844 Error = 3;
8845 break;
8846 case SC_Register:
8847 Error = 4;
8848 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008849 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008850 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008851 }
Richard Smith2316cd82011-09-29 19:11:37 +00008852 if (VD->isConstexpr())
8853 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008854 if (Error != -1) {
8855 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8856 << VD->getDeclName() << Error;
8857 D->setInvalidDecl();
8858 }
8859}
8860
John McCall8b7fd8f12011-01-19 11:48:09 +00008861void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8862 if (var->isInvalidDecl()) return;
8863
John McCall31168b02011-06-15 23:02:42 +00008864 // In ARC, don't allow jumps past the implicit initialization of a
8865 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008866 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008867 var->hasLocalStorage()) {
8868 switch (var->getType().getObjCLifetime()) {
8869 case Qualifiers::OCL_None:
8870 case Qualifiers::OCL_ExplicitNone:
8871 case Qualifiers::OCL_Autoreleasing:
8872 break;
8873
8874 case Qualifiers::OCL_Weak:
8875 case Qualifiers::OCL_Strong:
8876 getCurFunction()->setHasBranchProtectedScope();
8877 break;
8878 }
8879 }
8880
John McCall8a4e2e42014-01-29 08:33:09 +00008881 // Warn about externally-visible variables being defined without a
8882 // prior declaration. We only want to do this for global
8883 // declarations, but we also specifically need to avoid doing it for
8884 // class members because the linkage of an anonymous class can
8885 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008886 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008887 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008888 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008889 getDiagnostics().getDiagnosticLevel(
8890 diag::warn_missing_variable_declarations,
8891 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008892 // Find a previous declaration that's not a definition.
8893 VarDecl *prev = var->getPreviousDecl();
8894 while (prev && prev->isThisDeclarationADefinition())
8895 prev = prev->getPreviousDecl();
8896
8897 if (!prev)
8898 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8899 }
8900
Reid Kleckner92fc0172014-04-30 17:10:18 +00008901 if (var->getTLSKind() == VarDecl::TLS_Static) {
8902 if (var->getType().isDestructedType()) {
8903 // GNU C++98 edits for __thread, [basic.start.term]p3:
8904 // The type of an object with thread storage duration shall not
8905 // have a non-trivial destructor.
8906 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8907 if (getLangOpts().CPlusPlus11)
8908 Diag(var->getLocation(), diag::note_use_thread_local);
8909 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
8910 !var->getInit()->isConstantInitializer(
8911 Context, var->getType()->isReferenceType())) {
8912 // GNU C++98 edits for __thread, [basic.start.init]p4:
8913 // An object of thread storage duration shall not require dynamic
8914 // initialization.
8915 // FIXME: Need strict checking here.
8916 Diag(var->getLocation(), diag::err_thread_dynamic_init);
8917 if (getLangOpts().CPlusPlus11)
8918 Diag(var->getLocation(), diag::note_use_thread_local);
8919 }
8920
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008921 }
8922
Warren Huntc3b18962014-04-08 22:30:47 +00008923 if (var->isThisDeclarationADefinition() &&
8924 ActiveTemplateInstantiations.empty()) {
8925 PragmaStack<StringLiteral *> *Stack = nullptr;
8926 int SectionFlags = PSF_Implicit | PSF_Read;
8927 if (var->getType().isConstQualified())
8928 Stack = &ConstSegStack;
8929 else if (!var->getInit()) {
8930 Stack = &BSSSegStack;
8931 SectionFlags |= PSF_Write;
8932 } else {
8933 Stack = &DataSegStack;
8934 SectionFlags |= PSF_Write;
8935 }
8936 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
8937 var->addAttr(
8938 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8939 Stack->CurrentValue->getString(),
8940 Stack->CurrentPragmaLocation));
8941 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
8942 if (UnifySection(SA->getName(), SectionFlags, var))
8943 var->dropAttr<SectionAttr>();
8944 }
8945
John McCall8b7fd8f12011-01-19 11:48:09 +00008946 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008947 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008948
Richard Smithde63d362012-11-09 23:03:14 +00008949 QualType type = var->getType();
8950 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008951
8952 // __block variables might require us to capture a copy-initializer.
8953 if (var->hasAttr<BlocksAttr>()) {
8954 // It's currently invalid to ever have a __block variable with an
8955 // array type; should we diagnose that here?
8956
8957 // Regardless, we don't want to ignore array nesting when
8958 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008959 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008960 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008961 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008962 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008963 ExprResult result
8964 = PerformMoveOrCopyInitialization(
8965 InitializedEntity::InitializeBlock(poi, type, false),
8966 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008967 if (!result.isInvalid()) {
8968 result = MaybeCreateExprWithCleanups(result);
8969 Expr *init = result.takeAs<Expr>();
8970 Context.setBlockVarCopyInits(var, init);
8971 }
8972 }
8973 }
8974
Richard Smitheda3c842011-11-07 22:16:17 +00008975 Expr *Init = var->getInit();
8976 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008977 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008978
Richard Smithbf830092012-10-29 18:26:47 +00008979 if (!var->getDeclContext()->isDependentContext() &&
8980 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008981 if (IsGlobal && !var->isConstexpr() &&
8982 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8983 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008984 != DiagnosticsEngine::Ignored) {
8985 // Warn about globals which don't have a constant initializer. Don't
8986 // warn about globals with a non-trivial destructor because we already
8987 // warned about them.
8988 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8989 if (!(RD && !RD->hasTrivialDestructor()) &&
8990 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8991 Diag(var->getLocation(), diag::warn_global_constructor)
8992 << Init->getSourceRange();
8993 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008994
Richard Smithd0b4dd62011-12-19 06:19:21 +00008995 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008996 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008997 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8998 SourceLocation DiagLoc = var->getLocation();
8999 // If the note doesn't add any useful information other than a source
9000 // location, fold it into the primary diagnostic.
9001 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9002 diag::note_invalid_subexpr_in_const_expr) {
9003 DiagLoc = Notes[0].first;
9004 Notes.clear();
9005 }
9006 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9007 << var << Init->getSourceRange();
9008 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9009 Diag(Notes[I].first, Notes[I].second);
9010 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00009011 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009012 // Check whether the initializer of a const variable of integral or
9013 // enumeration type is an ICE now, since we can't tell whether it was
9014 // initialized by a constant expression if we check later.
9015 var->checkInitIsICE();
9016 }
Richard Smitheda3c842011-11-07 22:16:17 +00009017 }
John McCall8b7fd8f12011-01-19 11:48:09 +00009018
9019 // Require the destructor.
9020 if (const RecordType *recordType = baseType->getAs<RecordType>())
9021 FinalizeVarWithDestructor(var, recordType);
9022}
9023
Richard Smithb2bc2e62011-02-21 20:05:19 +00009024/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9025/// any semantic actions necessary after any initializer has been attached.
9026void
9027Sema::FinalizeDeclaration(Decl *ThisDecl) {
9028 // Note that we are no longer parsing the initializer for this declaration.
9029 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009030
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009031 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00009032 if (!VD)
9033 return;
9034
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00009035 checkAttributesAfterMerging(*this, *VD);
9036
Rafael Espindola87198cd2013-08-16 23:18:50 +00009037 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9038 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00009039 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00009040 VD->dropAttr<UsedAttr>();
9041 }
9042 }
9043
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009044 if (!VD->isInvalidDecl() &&
9045 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9046 if (const VarDecl *Def = VD->getDefinition()) {
9047 if (Def->hasAttr<AliasAttr>()) {
9048 Diag(VD->getLocation(), diag::err_tentative_after_alias)
9049 << VD->getDeclName();
9050 Diag(Def->getLocation(), diag::note_previous_definition);
9051 VD->setInvalidDecl();
9052 }
9053 }
9054 }
9055
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009056 const DeclContext *DC = VD->getDeclContext();
9057 // If there's a #pragma GCC visibility in scope, and this isn't a class
9058 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00009059 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009060 AddPushedVisibilityAttribute(VD);
9061
Richard Smithc3926172014-04-02 18:28:36 +00009062 // FIXME: Warn on unused templates.
Richard Smith6c6ef822014-04-25 19:21:40 +00009063 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9064 !isa<VarTemplatePartialSpecializationDecl>(VD))
Rafael Espindolad2ecc132013-01-03 04:29:20 +00009065 MarkUnusedFileScopedDecl(VD);
9066
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009067 // Now we have parsed the initializer and can update the table of magic
9068 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00009069 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9070 !VD->getType()->isIntegralOrEnumerationType())
9071 return;
9072
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00009073 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00009074 const Expr *MagicValueExpr = VD->getInit();
9075 if (!MagicValueExpr) {
9076 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009077 }
Rafael Espindola60470f12013-01-03 04:05:19 +00009078 llvm::APSInt MagicValueInt;
9079 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9080 Diag(I->getRange().getBegin(),
9081 diag::err_type_tag_for_datatype_not_ice)
9082 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9083 continue;
9084 }
9085 if (MagicValueInt.getActiveBits() > 64) {
9086 Diag(I->getRange().getBegin(),
9087 diag::err_type_tag_for_datatype_too_large)
9088 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9089 continue;
9090 }
9091 uint64_t MagicValue = MagicValueInt.getZExtValue();
9092 RegisterTypeTagForDatatype(I->getArgumentKind(),
9093 MagicValue,
9094 I->getMatchingCType(),
9095 I->getLayoutCompatible(),
9096 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009097 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00009098}
9099
Rafael Espindolaab417692013-07-09 12:05:01 +00009100Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9101 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009102 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009103
9104 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00009105 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009106
David Majnemer50ce8352013-09-17 23:57:10 +00009107 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009108 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00009109 if (Decl *D = Group[i]) {
9110 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9111 if (!FirstDeclaratorInGroup)
9112 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00009113 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00009114 }
Richard Smith2abf6762011-02-23 00:37:57 +00009115
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009116 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009117 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00009118 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00009119 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9120 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9121 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009122 }
David Blaikie095deba2012-11-14 01:52:05 +00009123
Rafael Espindolaab417692013-07-09 12:05:01 +00009124 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009125}
9126
9127/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9128/// group, performing any necessary semantic checking.
9129Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00009130Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009131 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009132 // C++0x [dcl.spec.auto]p7:
9133 // If the type deduced for the template parameter U is not the same in each
9134 // deduction, the program is ill-formed.
9135 // FIXME: When initializer-list support is added, a distinction is needed
9136 // between the deduced type U and the deduced type which 'auto' stands for.
9137 // auto a = 0, b = { 1, 2, 3 };
9138 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009139 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009140 QualType Deduced;
9141 CanQualType DeducedCanon;
9142 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009143 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009144 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9145 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009146 // Don't reissue diagnostics when instantiating a template.
9147 if (AT && D->isInvalidDecl())
9148 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009149 QualType U = AT ? AT->getDeducedType() : QualType();
9150 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009151 CanQualType UCanon = Context.getCanonicalType(U);
9152 if (Deduced.isNull()) {
9153 Deduced = U;
9154 DeducedCanon = UCanon;
9155 DeducedDecl = D;
9156 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009157 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9158 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009159 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009160 << Deduced << DeducedDecl->getDeclName()
9161 << U << D->getDeclName()
9162 << DeducedDecl->getInit()->getSourceRange()
9163 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009164 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009165 break;
9166 }
9167 }
9168 }
9169 }
9170 }
9171
Rafael Espindolaab417692013-07-09 12:05:01 +00009172 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009173
Rafael Espindolaab417692013-07-09 12:05:01 +00009174 return DeclGroupPtrTy::make(
9175 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009176}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009177
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009178void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009179 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009180}
9181
Rafael Espindolaab417692013-07-09 12:05:01 +00009182void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009183 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009184 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009185 return;
9186
9187 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9188 Group[0]->getLocation())
9189 == DiagnosticsEngine::Ignored)
9190 return;
9191
Rafael Espindolaab417692013-07-09 12:05:01 +00009192 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009193 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009194 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009195 // additional declaration references:
9196 // 'typedef struct S {} S;'
9197 // 'typedef struct S *S;'
9198 // 'struct S *pS;'
9199 // FinalizeDeclaratorGroup adds these as separate declarations.
9200 Decl *MaybeTagDecl = Group[0];
9201 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009202 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009203 }
9204 }
9205
9206 // See if there are any new comments that are not attached to a decl.
9207 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9208 if (!Comments.empty() &&
9209 !Comments.back()->isAttached()) {
9210 // There is at least one comment that not attached to a decl.
9211 // Maybe it should be attached to one of these decls?
9212 //
9213 // Note that this way we pick up not only comments that precede the
9214 // declaration, but also comments that *follow* the declaration -- thanks to
9215 // the lookahead in the lexer: we've consumed the semicolon and looked
9216 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009217 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009218 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009219 }
9220}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009221
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009222/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9223/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009224Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009225 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009226
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009227 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009228
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009229 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009230 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009231 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009232 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009233 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009234 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9235 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009236 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009237 Diag(DS.getStorageClassSpecLoc(),
9238 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009239 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009240 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009241
Richard Smithb4a9e862013-04-12 22:46:28 +00009242 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9243 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9244 << DeclSpec::getSpecifierName(TSCS);
9245 if (DS.isConstexprSpecified())
9246 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009247 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009248
Richard Smithb4a9e862013-04-12 22:46:28 +00009249 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009250
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009251 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009252 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009253
David Blaikiebbafb8a2012-03-11 07:00:24 +00009254 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009255 // Check that there are no default arguments inside the type of this
9256 // parameter.
9257 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009258
9259 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9260 if (D.getCXXScopeSpec().isSet()) {
9261 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9262 << D.getCXXScopeSpec().getRange();
9263 D.getCXXScopeSpec().clear();
9264 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009265 }
9266
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009267 // Ensure we have a valid name
9268 IdentifierInfo *II = 0;
9269 if (D.hasName()) {
9270 II = D.getIdentifier();
9271 if (!II) {
9272 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009273 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009274 D.setInvalidType(true);
9275 }
9276 }
9277
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009278 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009279 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009280 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9281 ForRedeclaration);
9282 LookupName(R, S);
9283 if (R.isSingleResult()) {
9284 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009285 if (PrevDecl->isTemplateParameter()) {
9286 // Maybe we will complain about the shadowed template parameter.
9287 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9288 // Just pretend that we didn't see the previous declaration.
9289 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009290 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009291 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009292 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009293
Chris Lattnerd9773512009-01-21 02:38:50 +00009294 // Recover by removing the name
9295 II = 0;
9296 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009297 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009298 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009299 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009300 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009301
John McCallf7b2fb52010-01-22 00:28:27 +00009302 // Temporarily put parameter variables in the translation unit, not
9303 // the enclosing context. This prevents them from accidentally
9304 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009305 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009306 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009307 D.getIdentifierLoc(), II,
9308 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009309 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009310
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009311 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009312 New->setInvalidDecl();
9313
9314 assert(S->isFunctionPrototypeScope());
9315 assert(S->getFunctionPrototypeDepth() >= 1);
9316 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9317 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009318
Douglas Gregor91f84212008-12-11 16:49:14 +00009319 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009320 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009321 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009322 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009323
Douglas Gregor758a8692009-06-17 21:51:59 +00009324 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009325
Douglas Gregor41866812011-09-12 18:37:38 +00009326 if (D.getDeclSpec().isModulePrivateSpecified())
9327 Diag(New->getLocation(), diag::err_module_private_local)
9328 << 1 << New->getDeclName()
9329 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9330 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9331
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009332 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009333 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9334 }
John McCall48871652010-08-21 09:40:31 +00009335 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009336}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009337
John McCalla3ccba02010-06-04 11:21:44 +00009338/// \brief Synthesizes a variable for a parameter arising from a
9339/// typedef.
9340ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9341 SourceLocation Loc,
9342 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009343 /* FIXME: setting StartLoc == Loc.
9344 Would it be worth to modify callers so as to provide proper source
9345 location for the unnamed parameters, embedding the parameter's type? */
9346 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009347 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009348 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009349 Param->setImplicit();
9350 return Param;
9351}
9352
John McCallc5990642010-08-24 09:05:15 +00009353void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9354 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009355 // Don't diagnose unused-parameter errors in template instantiations; we
9356 // will already have done so in the template itself.
9357 if (!ActiveTemplateInstantiations.empty())
9358 return;
9359
9360 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009361 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009362 !(*Param)->hasAttr<UnusedAttr>()) {
9363 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9364 << (*Param)->getDeclName();
9365 }
9366 }
9367}
9368
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009369void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9370 ParmVarDecl * const *ParamEnd,
9371 QualType ReturnTy,
9372 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009373 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009374 return;
9375
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009376 // Warn if the return value is pass-by-value and larger than the specified
9377 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009378 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009379 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009380 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009381 Diag(D->getLocation(), diag::warn_return_value_size)
9382 << D->getDeclName() << Size;
9383 }
9384
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009385 // Warn if any parameter is pass-by-value and larger than the specified
9386 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009387 for (; Param != ParamEnd; ++Param) {
9388 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009389 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009390 continue;
9391 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009392 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009393 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9394 << (*Param)->getDeclName() << Size;
9395 }
9396}
9397
Abramo Bagnaradff19302011-03-08 08:55:46 +00009398ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9399 SourceLocation NameLoc, IdentifierInfo *Name,
9400 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009401 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009402 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009403 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009404 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009405 T->isObjCLifetimeType()) {
9406
9407 Qualifiers::ObjCLifetime lifetime;
9408
9409 // Special cases for arrays:
9410 // - if it's const, use __unsafe_unretained
9411 // - otherwise, it's an error
9412 if (T->isArrayType()) {
9413 if (!T.isConstQualified()) {
9414 DelayedDiagnostics.add(
9415 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009416 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009417 }
9418 lifetime = Qualifiers::OCL_ExplicitNone;
9419 } else {
9420 lifetime = T->getObjCARCImplicitLifetime();
9421 }
9422 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009423 }
9424
Abramo Bagnaradff19302011-03-08 08:55:46 +00009425 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009426 Context.getAdjustedParameterType(T),
9427 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009428 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009429
9430 // Parameters can not be abstract class types.
9431 // For record types, this is done by the AbstractClassUsageDiagnoser once
9432 // the class has been completely parsed.
9433 if (!CurContext->isRecord() &&
9434 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9435 AbstractParamType))
9436 New->setInvalidDecl();
9437
9438 // Parameter declarators cannot be interface types. All ObjC objects are
9439 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009440 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009441 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009442 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009443 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009444 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009445 T = Context.getObjCObjectPointerType(T);
9446 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009447 }
9448
9449 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9450 // duration shall not be qualified by an address-space qualifier."
9451 // Since all parameters have automatic store duration, they can not have
9452 // an address space.
9453 if (T.getAddressSpace() != 0) {
Fraser Cormack01648e02014-04-15 11:38:29 +00009454 // OpenCL allows function arguments declared to be an array of a type
9455 // to be qualified with an address space.
9456 if (!(getLangOpts().OpenCL && T->isArrayType())) {
9457 Diag(NameLoc, diag::err_arg_with_address_space);
9458 New->setInvalidDecl();
9459 }
Douglas Gregor940bca72010-04-12 07:48:19 +00009460 }
9461
9462 return New;
9463}
9464
Douglas Gregor170512f2009-04-01 23:51:29 +00009465void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9466 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009467 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009468
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009469 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9470 // for a K&R function.
9471 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009472 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009473 --i;
Alp Tokerc5350722014-02-26 22:27:52 +00009474 if (FTI.Params[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009475 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009476 llvm::raw_svector_ostream(Code)
9477 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9478 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9479 << FTI.Params[i].Ident
9480 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009481
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009482 // Implicitly declare the argument as type 'int' for lack of a better
9483 // type.
John McCall084e83d2011-03-24 11:26:52 +00009484 AttributeFactory attrs;
9485 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009486 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009487 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009488 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9489 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009490 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009491 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9492 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009493 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009494 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9495 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009496 }
9497 }
Mike Stump11289f42009-09-09 15:08:12 +00009498 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009499}
9500
Richard Smith79a52e52012-04-17 22:30:01 +00009501Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009502 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009503 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009504 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009505
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009506 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009507 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009508 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009509}
9510
Anders Carlsson2a45e402012-12-18 01:29:20 +00009511static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9512 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009513 // Don't warn about invalid declarations.
9514 if (FD->isInvalidDecl())
9515 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009516
Anders Carlsson31c7e882009-12-09 03:30:09 +00009517 // Or declarations that aren't global.
9518 if (!FD->isGlobal())
9519 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009520
Anders Carlsson31c7e882009-12-09 03:30:09 +00009521 // Don't warn about C++ member functions.
9522 if (isa<CXXMethodDecl>(FD))
9523 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009524
Anders Carlsson31c7e882009-12-09 03:30:09 +00009525 // Don't warn about 'main'.
9526 if (FD->isMain())
9527 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009528
Anders Carlsson31c7e882009-12-09 03:30:09 +00009529 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009530 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009531 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009532
9533 // Don't warn about function templates.
9534 if (FD->getDescribedFunctionTemplate())
9535 return false;
9536
9537 // Don't warn about function template specializations.
9538 if (FD->isFunctionTemplateSpecialization())
9539 return false;
9540
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009541 // Don't warn for OpenCL kernels.
9542 if (FD->hasAttr<OpenCLKernelAttr>())
9543 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009544
Anders Carlsson31c7e882009-12-09 03:30:09 +00009545 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009546 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9547 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009548 // Ignore any declarations that occur in function or method
9549 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009550 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009551 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009552
Anders Carlsson31c7e882009-12-09 03:30:09 +00009553 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009554 if (FD->getNumParams() == 0)
9555 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009556 break;
9557 }
Richard Smith541b38b2013-09-20 01:15:31 +00009558
Anders Carlsson31c7e882009-12-09 03:30:09 +00009559 return MissingPrototype;
9560}
9561
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009562void
9563Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9564 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009565 // Don't complain if we're in GNU89 mode and the previous definition
9566 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009567 const FunctionDecl *Definition = EffectiveDefinition;
9568 if (!Definition)
9569 if (!FD->isDefined(Definition))
9570 return;
9571
9572 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009573 return;
9574
9575 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9576 Definition->getStorageClass() == SC_Extern)
9577 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009578 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009579 else
9580 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9581
9582 Diag(Definition->getLocation(), diag::note_previous_definition);
9583 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009584}
Faisal Valia17d19f2013-11-07 05:17:06 +00009585
9586
Faisal Valic1a6dc42013-10-23 16:10:50 +00009587static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9588 Sema &S) {
9589 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009590
9591 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009592 LSI->CallOperator = CallOperator;
9593 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009594 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009595 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9596
9597 if (LCD == LCD_None)
9598 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9599 else if (LCD == LCD_ByCopy)
9600 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9601 else if (LCD == LCD_ByRef)
9602 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9603 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9604
9605 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9606 LSI->Mutable = !CallOperator->isConst();
9607
Faisal Valia17d19f2013-11-07 05:17:06 +00009608 // Add the captures to the LSI so they can be noted as already
9609 // captured within tryCaptureVar.
Aaron Ballman6def98a2014-03-13 17:08:33 +00009610 for (const auto &C : LambdaClass->captures()) {
9611 if (C.capturesVariable()) {
9612 VarDecl *VD = C.getCapturedVar();
Faisal Valia17d19f2013-11-07 05:17:06 +00009613 if (VD->isInitCapture())
9614 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9615 QualType CaptureType = VD->getType();
Aaron Ballman6def98a2014-03-13 17:08:33 +00009616 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
Faisal Valia17d19f2013-11-07 05:17:06 +00009617 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
Aaron Ballman6def98a2014-03-13 17:08:33 +00009618 /*RefersToEnclosingLocal*/true, C.getLocation(),
9619 /*EllipsisLoc*/C.isPackExpansion()
9620 ? C.getEllipsisLoc() : SourceLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +00009621 CaptureType, /*Expr*/ 0);
9622
Aaron Ballman6def98a2014-03-13 17:08:33 +00009623 } else if (C.capturesThis()) {
9624 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +00009625 S.getCurrentThisType(), /*Expr*/ 0);
9626 }
9627 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009628}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009629
John McCall48871652010-08-21 09:40:31 +00009630Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009631 // Clear the last template instantiation error context.
9632 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9633
Douglas Gregor17a7c122009-06-24 00:54:41 +00009634 if (!D)
9635 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009636 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009637
John McCall48871652010-08-21 09:40:31 +00009638 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009639 FD = FunTmpl->getTemplatedDecl();
9640 else
John McCall48871652010-08-21 09:40:31 +00009641 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009642 // If we are instantiating a generic lambda call operator, push
9643 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009644 // that's already been calculated (ActOnLambdaExpr) to prime the current
9645 // LambdaScopeInfo.
9646 // When the template operator is being specialized, the LambdaScopeInfo,
9647 // has to be properly restored so that tryCaptureVariable doesn't try
9648 // and capture any new variables. In addition when calculating potential
9649 // captures during transformation of nested lambdas, it is necessary to
9650 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009651 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009652 assert(ActiveTemplateInstantiations.size() &&
9653 "There should be an active template instantiation on the stack "
9654 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009655 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009656 }
9657 else
9658 // Enter a new function scope
9659 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009660
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009661 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009662 if (!FD->isLateTemplateParsed())
9663 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009664
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009665 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009666 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009667 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9668 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009669 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009670 FD->setInvalidDecl();
9671 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009672 }
9673
Eli Friedman9ad72442009-03-04 07:30:59 +00009674 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009675 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009676 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009677 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009678 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009679 RequireCompleteType(FD->getLocation(), ResultType,
9680 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009681 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009682
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009683 // GNU warning -Wmissing-prototypes:
9684 // Warn if a global function is defined without a previous
9685 // prototype declaration. This warning is issued even if the
9686 // definition itself provides a prototype. The aim is to detect
9687 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009688 const FunctionDecl *PossibleZeroParamPrototype = 0;
9689 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009690 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009691
Anders Carlsson2a45e402012-12-18 01:29:20 +00009692 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009693 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009694 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009695 if (TypeSourceInfo *TI =
9696 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9697 TypeLoc TL = TI->getTypeLoc();
9698 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9699 Diag(PossibleZeroParamPrototype->getLocation(),
9700 diag::note_declaration_not_a_prototype)
9701 << PossibleZeroParamPrototype
9702 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9703 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009704 }
9705 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009706
Douglas Gregor67da0d92009-05-15 17:59:04 +00009707 if (FnBodyScope)
9708 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009709
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009710 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009711 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9712 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009713
9714 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00009715 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +00009716 Param->setOwningFunction(FD);
9717
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009718 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009719 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009720 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009721
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009722 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009723 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009724 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009725
James Molloy6f8780b2012-02-29 10:24:19 +00009726 // If we had any tags defined in the function prototype,
9727 // introduce them into the function scope.
9728 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009729 for (ArrayRef<NamedDecl *>::iterator
9730 I = FD->getDeclsInPrototypeScope().begin(),
9731 E = FD->getDeclsInPrototypeScope().end();
9732 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009733 NamedDecl *D = *I;
9734
9735 // Some of these decls (like enums) may have been pinned to the translation unit
9736 // for lack of a real context earlier. If so, remove from the translation unit
9737 // and reattach to the current context.
9738 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9739 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +00009740 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9741 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +00009742 Context.getTranslationUnitDecl()->removeDecl(D);
9743 break;
9744 }
9745 }
9746 // Either way, reassign the lexical decl context to our FunctionDecl.
9747 D->setLexicalDeclContext(CurContext);
9748 }
9749
9750 // If the decl has a non-null name, make accessible in the current scope.
9751 if (!D->getName().empty())
9752 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9753
9754 // Similarly, dive into enums and fish their constants out, making them
9755 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00009756 if (auto *ED = dyn_cast<EnumDecl>(D)) {
9757 for (auto *EI : ED->enumerators())
9758 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009759 }
9760 }
9761 }
9762
Richard Smith79a52e52012-04-17 22:30:01 +00009763 // Ensure that the function's exception specification is instantiated.
9764 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9765 ResolveExceptionSpec(D->getLocation(), FPT);
9766
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009767 // Checking attributes of current function definition
9768 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009769 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009770 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009771 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009772 // Microsoft accepts dllimport for functions defined within class scope.
9773 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009774 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009775 Diag(FD->getLocation(),
9776 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009777 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009778 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009779 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009780 }
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009781 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009782 // We want to attach documentation to original Decl (which might be
9783 // a function template).
9784 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009785 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009786}
9787
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009788/// \brief Given the set of return statements within a function body,
9789/// compute the variables that are subject to the named return value
9790/// optimization.
9791///
9792/// Each of the variables that is subject to the named return value
9793/// optimization will be marked as NRVO variables in the AST, and any
9794/// return statement that has a marked NRVO variable as its NRVO candidate can
9795/// use the named return value optimization.
9796///
9797/// This function applies a very simplistic algorithm for NRVO: if every return
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009798/// statement in the scope of a variable has the same NRVO candidate, that
9799/// candidate is an NRVO variable.
Douglas Gregor49695f02011-09-06 20:46:03 +00009800void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009801 ReturnStmt **Returns = Scope->Returns.data();
9802
John McCallaab3e412010-08-25 08:40:02 +00009803 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009804 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
9805 if (!NRVOCandidate->isNRVOVariable())
9806 Returns[I]->setNRVOCandidate(nullptr);
9807 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009808 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009809}
9810
Richard Smith8e6002f2014-03-12 23:14:33 +00009811bool Sema::canDelayFunctionBody(const Declarator &D) {
9812 // We can't delay parsing the body of a constexpr function template (yet).
9813 if (D.getDeclSpec().isConstexprSpecified())
9814 return false;
9815
9816 // We can't delay parsing the body of a function template with a deduced
9817 // return type (yet).
9818 if (D.getDeclSpec().containsPlaceholderType()) {
9819 // If the placeholder introduces a non-deduced trailing return type,
9820 // we can still delay parsing it.
9821 if (D.getNumTypeObjects()) {
9822 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9823 if (Outer.Kind == DeclaratorChunk::Function &&
9824 Outer.Fun.hasTrailingReturnType()) {
9825 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9826 return Ty.isNull() || !Ty->isUndeducedType();
9827 }
9828 }
9829 return false;
9830 }
9831
9832 return true;
9833}
9834
Richard Smith1ab34b32012-11-19 21:13:18 +00009835bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009836 // We cannot skip the body of a function (or function template) which is
9837 // constexpr, since we may need to evaluate its body in order to parse the
9838 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009839 // We cannot skip the body of a function with an undeduced return type,
9840 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009841 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009842 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009843 return false;
9844 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009845}
9846
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009847Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009848 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009849 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009850 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009851 MD->setHasSkippedBody();
9852 return ActOnFinishFunctionBody(Decl, 0);
9853}
9854
John McCallfaf5fb42010-08-26 23:41:50 +00009855Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009856 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009857}
9858
John McCallb268a282010-08-23 23:25:46 +00009859Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9860 bool IsInstantiation) {
Alp Tokera2794f92014-01-22 07:29:52 +00009861 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009862
Ted Kremenek0b405322010-03-23 00:13:23 +00009863 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009864 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009865
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009866 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009867 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009868
Richard Smith7500ab22013-05-10 04:31:10 +00009869 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009870 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009871 // If the function has a deduced result type but contains no 'return'
9872 // statements, the result type as written must be exactly 'auto', and
9873 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009874 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009875 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009876 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009877 FD->setInvalidDecl();
9878 } else {
9879 // Substitute 'void' for the 'auto' in the type.
9880 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009881 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009882 Context.adjustDeducedFunctionResultType(
9883 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009884 }
9885 }
9886
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009887 // The only way to be included in UndefinedButUsed is if there is an
9888 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009889 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009890 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009891 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009892 UndefinedButUsed.erase(FD);
9893 else if (FD->isInlined() &&
9894 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9895 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9896 UndefinedButUsed.erase(FD);
9897 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009898
John McCall5ed3caf2012-02-14 19:50:52 +00009899 // If the function implicitly returns zero (like 'main') or is naked,
9900 // don't complain about missing return statements.
9901 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009902 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009903
Francois Pichet3abc9b82011-05-11 02:14:46 +00009904 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009905 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009906 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009907 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9908
Douglas Gregor88d292c2010-05-13 16:44:06 +00009909 if (!FD->isInvalidDecl()) {
Reid Kleckner121b1a12014-04-30 16:31:28 +00009910 // Don't diagnose unused parameters of defaulted or deleted functions.
9911 if (Body)
9912 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009913 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009914 FD->getReturnType(), FD);
9915
Douglas Gregor88d292c2010-05-13 16:44:06 +00009916 // If this is a constructor, we need a vtable.
9917 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9918 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009919
Jordan Rosed39e5f12012-07-02 21:19:23 +00009920 // Try to apply the named return value optimization. We have to check
9921 // if we can do this here because lambdas keep return statements around
9922 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +00009923 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +00009924 !FD->isDependentContext())
9925 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009926 }
9927
Douglas Gregor21f46922012-02-08 20:17:14 +00009928 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9929 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009930 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009931 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009932 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009933 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009934 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009935 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009936 MD->getReturnType(), MD);
9937
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009938 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009939 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009940 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009941 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009942 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9943 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009944 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009945 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009946 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9947 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009948 bool isDesignated =
9949 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009950 assert(isDesignated && InitMethod);
9951 (void)isDesignated;
Argyrios Kyrtzidisde103662014-04-16 18:32:51 +00009952
9953 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
9954 auto IFace = MD->getClassInterface();
9955 if (!IFace)
9956 return false;
9957 auto SuperD = IFace->getSuperClass();
9958 if (!SuperD)
9959 return false;
9960 return SuperD->getIdentifier() ==
9961 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
9962 };
9963 // Don't issue this warning for unavailable inits or direct subclasses
9964 // of NSObject.
9965 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +00009966 Diag(MD->getLocation(),
9967 diag::warn_objc_designated_init_missing_super_call);
9968 Diag(InitMethod->getLocation(),
9969 diag::note_objc_designated_init_marked_here);
9970 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009971 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9972 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009973 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +00009974 // Don't issue this warning for unavaialable inits.
9975 if (!MD->isUnavailable())
9976 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009977 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9978 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009979 } else {
John McCall48871652010-08-21 09:40:31 +00009980 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009981 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009982
Jordan Rose2afd6612012-10-19 16:05:26 +00009983 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009984 "This should only be set for ObjC methods, which should have been "
9985 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009986
Chris Lattnere2473062007-05-28 06:28:18 +00009987 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009988 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009989 // C++ constructors that have function-try-blocks can't have return
9990 // statements in the handlers of that block. (C++ [except.handle]p14)
9991 // Verify this.
9992 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9993 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9994
Richard Smithdef8bdb2011-08-12 18:44:32 +00009995 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009996 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009997 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009998 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009999
John McCalldeb646e2010-08-04 01:04:25 +000010000 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10001 if (!Destructor->getParent()->isDependentType())
10002 CheckDestructor(Destructor);
10003
John McCalla6309952010-03-16 21:39:52 +000010004 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10005 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +000010006 }
Douglas Gregor9a28e842010-03-01 23:15:13 +000010007
10008 // If any errors have occurred, clear out any temporaries that may have
10009 // been leftover. This ensures that these temporaries won't be picked up for
10010 // deletion in some later function.
Alp Tokerb6cc5922014-05-03 03:45:55 +000010011 if (getDiagnostics().hasErrorOccurred() ||
10012 getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +000010013 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010014 }
Alp Tokerb6cc5922014-05-03 03:45:55 +000010015 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010016 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +000010017 // Since the body is valid, issue any analysis-based warnings that are
10018 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +000010019 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +000010020 }
10021
Richard Smith3607ffe2012-02-13 03:54:03 +000010022 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10023 (!CheckConstexprFunctionDecl(FD) ||
10024 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +000010025 FD->setInvalidDecl();
10026
John McCall28fc7092011-11-10 05:35:25 +000010027 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +000010028 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +000010029 assert(MaybeODRUseExprs.empty() &&
10030 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +000010031 }
10032
John McCalle99d5f32010-03-25 22:08:03 +000010033 if (!IsInstantiation)
10034 PopDeclContext();
10035
Eli Friedman71c80552012-01-05 03:35:19 +000010036 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +000010037 // If any errors have occurred, clear out any temporaries that may have
10038 // been leftover. This ensures that these temporaries won't be picked up for
10039 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +000010040 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +000010041 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +000010042 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +000010043
John McCall48871652010-08-21 09:40:31 +000010044 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +000010045}
10046
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010047
10048/// When we finish delayed parsing of an attribute, we must attach it to the
10049/// relevant Decl.
10050void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10051 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000010052 // Always attach attributes to the underlying decl.
10053 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10054 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +000010055 ProcessDeclAttributeList(S, D, Attrs.getList());
10056
10057 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10058 if (Method->isStatic())
10059 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010060}
10061
10062
Chris Lattnerac18be92006-11-20 06:49:47 +000010063/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10064/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +000010065NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +000010066 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010067 // Before we produce a declaration for an implicitly defined
10068 // function, see whether there was a locally-scoped declaration of
10069 // this name as a function or variable. If so, use that
10070 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +000010071 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10072 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10073 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10074 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010075 }
10076
Chris Lattner00e26072008-05-05 21:18:06 +000010077 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +000010078 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +000010079 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +000010080 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010081 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +000010082 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +000010083 else
Hans Wennborg70a13242011-12-08 15:56:07 +000010084 diag_id = diag::warn_implicit_function_decl;
10085 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +000010086
Hans Wennborg70a13242011-12-08 15:56:07 +000010087 // Because typo correction is expensive, only do it if the implicit
10088 // function declaration is going to be treated as an error.
10089 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10090 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000010091 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +000010092 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
John Thompson2255f2c2014-04-23 12:57:01 +000010093 LookupOrdinaryName, S, 0, Validator,
10094 CTK_NonError)))
Richard Smithf9b15102013-08-17 00:46:16 +000010095 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10096 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +000010097 }
10098
Chris Lattnerac18be92006-11-20 06:49:47 +000010099 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +000010100 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +000010101 AttributeFactory attrFactory;
10102 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +000010103 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +000010104 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10105 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010106 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +000010107 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010108 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +000010109 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010110 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10111 /*IsAmbiguous=*/false,
Richard Smith151b8a32014-04-07 15:16:58 +000010112 /*LParenLoc=*/NoLoc,
10113 /*Params=*/0,
10114 /*NumParams=*/0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010115 /*EllipsisLoc=*/NoLoc,
10116 /*RParenLoc=*/NoLoc,
10117 /*TypeQuals=*/0,
10118 /*RefQualifierIsLvalueRef=*/true,
10119 /*RefQualifierLoc=*/NoLoc,
10120 /*ConstQualifierLoc=*/NoLoc,
10121 /*VolatileQualifierLoc=*/NoLoc,
10122 /*MutableLoc=*/NoLoc,
10123 EST_None,
10124 /*ESpecLoc=*/NoLoc,
10125 /*Exceptions=*/0,
10126 /*ExceptionRanges=*/0,
10127 /*NumExceptions=*/0,
10128 /*NoexceptExpr=*/0,
10129 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +000010130 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010131 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010132 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010133
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010134 // Insert this function into translation-unit scope.
10135
10136 DeclContext *PrevDC = CurContext;
10137 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010138
Jordan Rosed03d99d2013-03-05 01:27:54 +000010139 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010140 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010141
10142 CurContext = PrevDC;
10143
Douglas Gregore711f702009-02-14 18:57:46 +000010144 AddKnownFunctionAttributes(FD);
10145
Steve Naroff3913ea42008-04-04 14:32:09 +000010146 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010147}
10148
Douglas Gregore711f702009-02-14 18:57:46 +000010149/// \brief Adds any function attributes that we know a priori based on
10150/// the declaration of this function.
10151///
10152/// These attributes can apply both to implicitly-declared builtins
10153/// (like __builtin___printf_chk) or to library-declared functions
10154/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010155///
10156/// We need to check for duplicate attributes both here and where user-written
10157/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010158void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10159 if (FD->isInvalidDecl())
10160 return;
10161
10162 // If this is a built-in function, map its builtin attributes to
10163 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010164 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010165 // Handle printf-formatting attributes.
10166 unsigned FormatIdx;
10167 bool HasVAListArg;
10168 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010169 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010170 const char *fmt = "printf";
10171 unsigned int NumParams = FD->getNumParams();
10172 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10173 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10174 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010175 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010176 &Context.Idents.get(fmt),
10177 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010178 HasVAListArg ? 0 : FormatIdx+2,
10179 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010180 }
Douglas Gregore711f702009-02-14 18:57:46 +000010181 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010182 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10183 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010184 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010185 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010186 &Context.Idents.get("scanf"),
10187 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010188 HasVAListArg ? 0 : FormatIdx+2,
10189 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010190 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010191
10192 // Mark const if we don't care about errno and that is the only
10193 // thing preventing the function from being const. This allows
10194 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010195 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010196 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010197 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010198 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010199 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010200
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010201 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010202 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010203 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10204 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010205 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010206 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010207 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010208 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010209 }
10210
10211 IdentifierInfo *Name = FD->getIdentifier();
10212 if (!Name)
10213 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010214 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010215 FD->getDeclContext()->isTranslationUnit()) ||
10216 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010217 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010218 LinkageSpecDecl::lang_c)) {
10219 // Okay: this could be a libc/libm/Objective-C function we know
10220 // about.
10221 } else
10222 return;
10223
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010224 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010225 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010226 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010227 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010228 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010229 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010230 Name->isStr("vasprintf") ? 0 : 3,
10231 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010232 }
Jordan Rose742c6072012-08-08 21:17:31 +000010233
10234 if (Name->isStr("__CFStringMakeConstantString")) {
10235 // We already have a __builtin___CFStringMakeConstantString,
10236 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010237 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010238 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10239 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010240 }
Douglas Gregore711f702009-02-14 18:57:46 +000010241}
Chris Lattner302b4be2006-11-19 02:31:38 +000010242
John McCall703a3f82009-10-24 08:00:42 +000010243TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010244 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010245 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010246 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010247
John McCallbcd03502009-12-07 02:54:59 +000010248 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010249 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010250 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010251 }
10252
Chris Lattner18b19622007-01-22 07:39:13 +000010253 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010254 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010255 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010256 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010257 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010258 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010259
John McCall04fcd0d2011-02-01 08:20:08 +000010260 // Bail out immediately if we have an invalid declaration.
10261 if (D.isInvalidType()) {
10262 NewTD->setInvalidDecl();
10263 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010264 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010265
Douglas Gregor41866812011-09-12 18:37:38 +000010266 if (D.getDeclSpec().isModulePrivateSpecified()) {
10267 if (CurContext->isFunctionOrMethod())
10268 Diag(NewTD->getLocation(), diag::err_module_private_local)
10269 << 2 << NewTD->getDeclName()
10270 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10271 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10272 else
10273 NewTD->setModulePrivate();
10274 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010275
John McCall04fcd0d2011-02-01 08:20:08 +000010276 // C++ [dcl.typedef]p8:
10277 // If the typedef declaration defines an unnamed class (or
10278 // enum), the first typedef-name declared by the declaration
10279 // to be that class type (or enum type) is used to denote the
10280 // class type (or enum type) for linkage purposes only.
10281 // We need to check whether the type was declared in the declaration.
10282 switch (D.getDeclSpec().getTypeSpecType()) {
10283 case TST_enum:
10284 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010285 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010286 case TST_union:
10287 case TST_class: {
10288 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10289
10290 // Do nothing if the tag is not anonymous or already has an
10291 // associated typedef (from an earlier typedef in this decl group).
10292 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010293 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010294
10295 // A well-formed anonymous tag must always be a TUK_Definition.
10296 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10297
10298 // The type must match the tag exactly; no qualifiers allowed.
10299 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10300 break;
10301
John McCall2575d882014-01-30 01:12:53 +000010302 // If we've already computed linkage for the anonymous tag, then
10303 // adding a typedef name for the anonymous decl can change that
10304 // linkage, which might be a serious problem. Diagnose this as
10305 // unsupported and ignore the typedef name. TODO: we should
10306 // pursue this as a language defect and establish a formal rule
10307 // for how to handle it.
10308 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10309 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10310
10311 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +000010312 tagLoc = getLocForEndOfToken(tagLoc);
John McCall2575d882014-01-30 01:12:53 +000010313
10314 llvm::SmallString<40> textToInsert;
10315 textToInsert += ' ';
10316 textToInsert += D.getIdentifier()->getName();
10317 Diag(tagLoc, diag::note_typedef_changes_linkage)
10318 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10319 break;
10320 }
10321
John McCall04fcd0d2011-02-01 08:20:08 +000010322 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010323 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010324 break;
10325 }
10326
10327 default:
10328 break;
10329 }
10330
Steve Narofff93b6722007-08-28 20:14:24 +000010331 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010332}
10333
Douglas Gregord9034f02009-05-14 16:41:31 +000010334
Richard Smith4b38ded2012-03-14 23:13:10 +000010335/// \brief Check that this is a valid underlying type for an enum declaration.
10336bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10337 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10338 QualType T = TI->getType();
10339
Eli Friedman52f32b92012-12-18 02:37:32 +000010340 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010341 return false;
10342
Eli Friedman52f32b92012-12-18 02:37:32 +000010343 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10344 if (BT->isInteger())
10345 return false;
10346
Richard Smith4b38ded2012-03-14 23:13:10 +000010347 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10348 return true;
10349}
10350
10351/// Check whether this is a valid redeclaration of a previous enumeration.
10352/// \return true if the redeclaration was invalid.
10353bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10354 QualType EnumUnderlyingTy,
10355 const EnumDecl *Prev) {
10356 bool IsFixed = !EnumUnderlyingTy.isNull();
10357
10358 if (IsScoped != Prev->isScoped()) {
10359 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10360 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010361 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010362 return true;
10363 }
10364
10365 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010366 if (!EnumUnderlyingTy->isDependentType() &&
10367 !Prev->getIntegerType()->isDependentType() &&
10368 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010369 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010370 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010371 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10372 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010373 Diag(Prev->getLocation(), diag::note_previous_declaration)
10374 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010375 return true;
10376 }
10377 } else if (IsFixed != Prev->isFixed()) {
10378 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10379 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010380 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010381 return true;
10382 }
10383
10384 return false;
10385}
10386
Joao Matosdc86f942012-08-31 18:45:21 +000010387/// \brief Get diagnostic %select index for tag kind for
10388/// redeclaration diagnostic message.
10389/// WARNING: Indexes apply to particular diagnostics only!
10390///
10391/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010392static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010393 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010394 case TTK_Struct: return 0;
10395 case TTK_Interface: return 1;
10396 case TTK_Class: return 2;
10397 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010398 }
Joao Matosdc86f942012-08-31 18:45:21 +000010399}
10400
10401/// \brief Determine if tag kind is a class-key compatible with
10402/// class for redeclaration (class, struct, or __interface).
10403///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010404/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010405static bool isClassCompatTagKind(TagTypeKind Tag)
10406{
10407 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10408}
10409
Douglas Gregord9034f02009-05-14 16:41:31 +000010410/// \brief Determine whether a tag with a given kind is acceptable
10411/// as a redeclaration of the given tag declaration.
10412///
10413/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010414bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010415 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010416 SourceLocation NewTagLoc,
10417 const IdentifierInfo &Name) {
10418 // C++ [dcl.type.elab]p3:
10419 // The class-key or enum keyword present in the
10420 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010421 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010422 // refers. This rule also applies to the form of
10423 // elaborated-type-specifier that declares a class-name or
10424 // friend class since it can be construed as referring to the
10425 // definition of the class. Thus, in any
10426 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010427 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010428 // used to refer to a union (clause 9), and either the class or
10429 // struct class-key shall be used to refer to a class (clause 9)
10430 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010431 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010432 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010433 if (OldTag == NewTag)
10434 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010435
Joao Matosdc86f942012-08-31 18:45:21 +000010436 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010437 // Warn about the struct/class tag mismatch.
10438 bool isTemplate = false;
10439 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10440 isTemplate = Record->getDescribedClassTemplate();
10441
Richard Trieucaa33d32011-06-10 03:11:26 +000010442 if (!ActiveTemplateInstantiations.empty()) {
10443 // In a template instantiation, do not offer fix-its for tag mismatches
10444 // since they usually mess up the template instead of fixing the problem.
10445 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010446 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10447 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010448 return true;
10449 }
10450
10451 if (isDefinition) {
10452 // On definitions, check previous tags and issue a fix-it for each
10453 // one that doesn't match the current tag.
10454 if (Previous->getDefinition()) {
10455 // Don't suggest fix-its for redefinitions.
10456 return true;
10457 }
10458
10459 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010460 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010461 if (I->getTagKind() != NewTag) {
10462 if (!previousMismatch) {
10463 previousMismatch = true;
10464 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010465 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10466 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010467 }
10468 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010469 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010470 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010471 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010472 }
10473 }
10474 return true;
10475 }
10476
10477 // Check for a previous definition. If current tag and definition
10478 // are same type, do nothing. If no definition, but disagree with
10479 // with previous tag type, give a warning, but no fix-it.
10480 const TagDecl *Redecl = Previous->getDefinition() ?
10481 Previous->getDefinition() : Previous;
10482 if (Redecl->getTagKind() == NewTag) {
10483 return true;
10484 }
10485
Douglas Gregord9034f02009-05-14 16:41:31 +000010486 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010487 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10488 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010489 Diag(Redecl->getLocation(), diag::note_previous_use);
10490
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010491 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010492 if (Previous->getDefinition()) {
10493 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010494 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010495 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010496 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010497 }
10498
Douglas Gregord9034f02009-05-14 16:41:31 +000010499 return true;
10500 }
10501 return false;
10502}
10503
Steve Naroff30d242c2007-09-15 18:49:24 +000010504/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010505/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010506/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010507/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010508///
10509/// IsTypeSpecifier is true if this is a type-specifier (or
10510/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010511Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010512 SourceLocation KWLoc, CXXScopeSpec &SS,
10513 IdentifierInfo *Name, SourceLocation NameLoc,
10514 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010515 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010516 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010517 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010518 SourceLocation ScopedEnumKWLoc,
10519 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010520 TypeResult UnderlyingType,
10521 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010522 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010523 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010524 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010525 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010526 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010527
Douglas Gregord6ab8742009-05-28 23:31:59 +000010528 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010529 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010530 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010531
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010532 // FIXME: Check explicit specializations more carefully.
10533 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010534 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010535
10536 // We only need to do this matching if we have template parameters
10537 // or a scope specifier, which also conveniently avoids this work
10538 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010539 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010540 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010541 if (TemplateParameterList *TemplateParams =
10542 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +000010543 KWLoc, NameLoc, SS, 0, TemplateParameterLists,
10544 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010545 if (Kind == TTK_Enum) {
10546 Diag(KWLoc, diag::err_enum_template);
10547 return 0;
10548 }
10549
Douglas Gregor3dad8422009-09-26 06:47:28 +000010550 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010551 // This is a declaration or definition of a class template (which may
10552 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010553
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010554 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010555 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010556
Douglas Gregore93e46c2009-07-22 23:48:44 +000010557 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010558 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010559 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010560 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010561 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010562 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010563 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010564 return Result.get();
10565 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010566 // The "template<>" header is extraneous.
10567 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010568 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010569 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010570 }
Mike Stump11289f42009-09-09 15:08:12 +000010571 }
10572 }
10573
Douglas Gregor0bf31402010-10-08 23:50:27 +000010574 // Figure out the underlying type if this a enum declaration. We need to do
10575 // this early, because it's needed to detect if this is an incompatible
10576 // redeclaration.
10577 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10578
10579 if (Kind == TTK_Enum) {
10580 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10581 // No underlying type explicitly specified, or we failed to parse the
10582 // type, default to int.
10583 EnumUnderlying = Context.IntTy.getTypePtr();
10584 else if (UnderlyingType.get()) {
10585 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10586 // integral type; any cv-qualification is ignored.
10587 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010588 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010589 EnumUnderlying = TI;
10590
Richard Smith4b38ded2012-03-14 23:13:10 +000010591 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010592 // Recover by falling back to int.
10593 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010594
Richard Smith4b38ded2012-03-14 23:13:10 +000010595 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010596 UPPC_FixedUnderlyingType))
10597 EnumUnderlying = Context.IntTy.getTypePtr();
10598
Alp Tokerbfa39342014-01-14 12:51:41 +000010599 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010600 // Microsoft enums are always of int type.
10601 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010602 }
10603
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010604 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010605 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010606 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010607
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010608 RedeclarationKind Redecl = ForRedeclaration;
10609 if (TUK == TUK_Friend || TUK == TUK_Reference)
10610 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010611
10612 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010613 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010614 if (Name && SS.isNotEmpty()) {
10615 // We have a nested-name tag ('struct foo::bar').
10616
10617 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010618 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010619 Name = 0;
10620 goto CreateNewDecl;
10621 }
10622
John McCall7f41d982009-09-11 04:59:25 +000010623 // If this is a friend or a reference to a class in a dependent
10624 // context, don't try to make a decl for it.
10625 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10626 DC = computeDeclContext(SS, false);
10627 if (!DC) {
10628 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010629 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010630 }
John McCall0b66eb32010-05-01 00:40:08 +000010631 } else {
10632 DC = computeDeclContext(SS, true);
10633 if (!DC) {
10634 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10635 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010636 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010637 }
John McCall7f41d982009-09-11 04:59:25 +000010638 }
10639
John McCall0b66eb32010-05-01 00:40:08 +000010640 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010641 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010642
Douglas Gregor8761da52009-02-03 00:34:39 +000010643 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010644 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010645 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010646
John McCall1f82f242009-11-18 22:49:29 +000010647 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010648 return 0;
John McCall6538c932009-10-10 05:48:19 +000010649
John McCall1f82f242009-11-18 22:49:29 +000010650 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010651 // Name lookup did not find anything. However, if the
10652 // nested-name-specifier refers to the current instantiation,
10653 // and that current instantiation has any dependent base
10654 // classes, we might find something at instantiation time: treat
10655 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010656 // But this only makes any sense for reference-like lookups.
10657 if (Previous.wasNotFoundInCurrentInstantiation() &&
10658 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010659 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010660 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010661 }
10662
10663 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010664 Diag(NameLoc, diag::err_not_tag_in_scope)
10665 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010666 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010667 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010668 goto CreateNewDecl;
10669 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010670 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010671 // If this is a named struct, check to see if there was a previous forward
10672 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010673 // FIXME: We're looking into outer scopes here, even when we
10674 // shouldn't be. Doing so can result in ambiguities that we
10675 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010676 LookupName(Previous, S);
10677
John McCall3c581bf2013-03-20 01:53:00 +000010678 // When declaring or defining a tag, ignore ambiguities introduced
10679 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010680 if (Previous.isAmbiguous() &&
10681 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010682 LookupResult::Filter F = Previous.makeFilter();
10683 while (F.hasNext()) {
10684 NamedDecl *ND = F.next();
10685 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10686 F.erase();
10687 }
10688 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010689 }
John McCall3c581bf2013-03-20 01:53:00 +000010690
10691 // C++11 [namespace.memdef]p3:
10692 // If the name in a friend declaration is neither qualified nor
10693 // a template-id and the declaration is a function or an
10694 // elaborated-type-specifier, the lookup to determine whether
10695 // the entity has been previously declared shall not consider
10696 // any scopes outside the innermost enclosing namespace.
10697 //
10698 // Does it matter that this should be by scope instead of by
10699 // semantic context?
10700 if (!Previous.empty() && TUK == TUK_Friend) {
10701 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10702 LookupResult::Filter F = Previous.makeFilter();
10703 while (F.hasNext()) {
10704 NamedDecl *ND = F.next();
10705 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010706 if (DC->isFileContext() &&
10707 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010708 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010709 FriendSawTagOutsideEnclosingNamespace = true;
10710 }
John McCall3c581bf2013-03-20 01:53:00 +000010711 }
10712 F.done();
10713 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010714
John McCall1f82f242009-11-18 22:49:29 +000010715 // Note: there used to be some attempt at recovery here.
10716 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010717 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010718
David Blaikiebbafb8a2012-03-11 07:00:24 +000010719 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010720 // FIXME: This makes sure that we ignore the contexts associated
10721 // with C structs, unions, and enums when looking for a matching
10722 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010723 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010724 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10725 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010726 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010727 } else if (S->isFunctionPrototypeScope()) {
10728 // If this is an enum declaration in function prototype scope, set its
10729 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010730 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010731 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010732 }
10733
John McCall1f82f242009-11-18 22:49:29 +000010734 if (Previous.isSingleResult() &&
10735 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010736 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010737 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010738 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010739 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010740 }
10741
David Blaikiebbafb8a2012-03-11 07:00:24 +000010742 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010743 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010744 // This is a declaration of or a reference to "std::bad_alloc".
10745 isStdBadAlloc = true;
10746
John McCall1f82f242009-11-18 22:49:29 +000010747 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010748 // std::bad_alloc has been implicitly declared (but made invisible to
10749 // name lookup). Fill in this implicit declaration as the previous
10750 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010751 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010752 }
10753 }
John McCall1f82f242009-11-18 22:49:29 +000010754
John McCalle9eaf8e2010-03-25 21:28:06 +000010755 // If we didn't find a previous declaration, and this is a reference
10756 // (or friend reference), move to the correct scope. In C++, we
10757 // also need to do a redeclaration lookup there, just in case
10758 // there's a shadow friend decl.
10759 if (Name && Previous.empty() &&
10760 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10761 if (Invalid) goto CreateNewDecl;
10762 assert(SS.isEmpty());
10763
10764 if (TUK == TUK_Reference) {
10765 // C++ [basic.scope.pdecl]p5:
10766 // -- for an elaborated-type-specifier of the form
10767 //
10768 // class-key identifier
10769 //
10770 // if the elaborated-type-specifier is used in the
10771 // decl-specifier-seq or parameter-declaration-clause of a
10772 // function defined in namespace scope, the identifier is
10773 // declared as a class-name in the namespace that contains
10774 // the declaration; otherwise, except as a friend
10775 // declaration, the identifier is declared in the smallest
10776 // non-class, non-function-prototype scope that contains the
10777 // declaration.
10778 //
10779 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10780 // C structs and unions.
10781 //
10782 // It is an error in C++ to declare (rather than define) an enum
10783 // type, including via an elaborated type specifier. We'll
10784 // diagnose that later; for now, declare the enum in the same
10785 // scope as we would have picked for any other tag type.
10786 //
10787 // GNU C also supports this behavior as part of its incomplete
10788 // enum types extension, while GNU C++ does not.
10789 //
10790 // Find the context where we'll be declaring the tag.
10791 // FIXME: We would like to maintain the current DeclContext as the
10792 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010793 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010794 SearchDC = SearchDC->getParent();
10795
10796 // Find the scope where we'll be declaring the tag.
10797 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010798 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010799 S->isFunctionPrototypeScope()) ||
10800 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010801 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010802 S = S->getParent();
10803 } else {
10804 assert(TUK == TUK_Friend);
10805 // C++ [namespace.memdef]p3:
10806 // If a friend declaration in a non-local class first declares a
10807 // class or function, the friend class or function is a member of
10808 // the innermost enclosing namespace.
10809 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010810 }
10811
John McCalle87beb22010-04-23 18:46:30 +000010812 // In C++, we need to do a redeclaration lookup to properly
10813 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010814 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010815 Previous.setRedeclarationKind(ForRedeclaration);
10816 LookupQualifiedName(Previous, SearchDC);
10817 }
10818 }
10819
John McCall1f82f242009-11-18 22:49:29 +000010820 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010821 NamedDecl *PrevDecl = Previous.getFoundDecl();
10822 NamedDecl *DirectPrevDecl =
10823 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010824
10825 // It's okay to have a tag decl in the same scope as a typedef
10826 // which hides a tag decl in the same scope. Finding this
10827 // insanity with a redeclaration lookup can only actually happen
10828 // in C++.
10829 //
10830 // This is also okay for elaborated-type-specifiers, which is
10831 // technically forbidden by the current standard but which is
10832 // okay according to the likely resolution of an open issue;
10833 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010834 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010835 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010836 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10837 TagDecl *Tag = TT->getDecl();
10838 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010839 Tag->getDeclContext()->getRedeclContext()
10840 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010841 PrevDecl = Tag;
10842 Previous.clear();
10843 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010844 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010845 }
10846 }
10847 }
10848 }
10849
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010850 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010851 // If this is a use of a previous tag, or if the tag is already declared
10852 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010853 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010854 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010855 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010856 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010857 // Make sure that this wasn't declared as an enum and now used as a
10858 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010859 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10860 TUK == TUK_Definition, KWLoc,
10861 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010862 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010863 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10864 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010865 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010866 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010867 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010868 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10869 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010870 else
10871 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010872 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010873
Mike Stump11289f42009-09-09 15:08:12 +000010874 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010875 Kind = PrevTagDecl->getTagKind();
10876 else {
10877 // Recover by making this an anonymous redefinition.
10878 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010879 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010880 Invalid = true;
10881 }
10882 }
10883
Douglas Gregor0bf31402010-10-08 23:50:27 +000010884 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10885 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10886
Richard Smith0f8ee222012-01-10 01:33:14 +000010887 // If this is an elaborated-type-specifier for a scoped enumeration,
10888 // the 'class' keyword is not necessary and not permitted.
10889 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10890 if (ScopedEnum)
10891 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10892 << PrevEnum->isScoped()
10893 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10894 return PrevTagDecl;
10895 }
10896
Richard Smith4b38ded2012-03-14 23:13:10 +000010897 QualType EnumUnderlyingTy;
10898 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010899 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010900 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10901 EnumUnderlyingTy = QualType(T, 0);
10902
Douglas Gregor0bf31402010-10-08 23:50:27 +000010903 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010904 // returning the previous declaration, unless this is a definition,
10905 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010906 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10907 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010908 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010909 }
10910
David Majnemer55890bf2013-06-11 03:51:23 +000010911 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010912 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010913 // except that a nested class or member class template can be declared
10914 // and then later defined.
10915 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10916 S->isDeclScope(PrevDecl)) {
10917 Diag(NameLoc, diag::ext_member_redeclared);
10918 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10919 }
10920
Douglas Gregor170512f2009-04-01 23:51:29 +000010921 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010922 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010923
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010924 // FIXME: In the future, return a variant or some other clue
10925 // for the consumer of this Decl to know it doesn't own it.
10926 // For our current ASTs this shouldn't be a problem, but will
10927 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010928 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010929 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010930 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010931
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010932 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010933 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010934 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010935 // If we're defining a specialization and the previous definition
10936 // is from an implicit instantiation, don't emit an error
10937 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010938 bool IsExplicitSpecializationAfterInstantiation = false;
10939 if (isExplicitSpecialization) {
10940 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10941 IsExplicitSpecializationAfterInstantiation =
10942 RD->getTemplateSpecializationKind() !=
10943 TSK_ExplicitSpecialization;
10944 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10945 IsExplicitSpecializationAfterInstantiation =
10946 ED->getTemplateSpecializationKind() !=
10947 TSK_ExplicitSpecialization;
10948 }
10949
10950 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010951 // A redeclaration in function prototype scope in C isn't
10952 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010953 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010954 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10955 else
10956 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010957 Diag(Def->getLocation(), diag::note_previous_definition);
10958 // If this is a redefinition, recover by making this
10959 // struct be anonymous, which will make any later
10960 // references get the previous definition.
10961 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010962 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010963 Invalid = true;
10964 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010965 } else {
10966 // If the type is currently being defined, complain
10967 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010968 const TagType *Tag
10969 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010970 if (Tag->isBeingDefined()) {
10971 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010972 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010973 diag::note_previous_definition);
10974 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010975 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010976 Invalid = true;
10977 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010978 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010979
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010980 // Okay, this is definition of a previously declared or referenced
10981 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010982 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010983 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010984 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010985 // have a definition. Just create a new decl.
10986
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010987 } else {
10988 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010989 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010990 // new decl/type. We set PrevDecl to NULL so that the entities
10991 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010992 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010993 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010994 // If we get here, we're going to create a new Decl. If PrevDecl
10995 // is non-NULL, it's a definition of the tag declared by
10996 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010997
10998
10999 // Otherwise, PrevDecl is not a tag, but was found with tag
11000 // lookup. This is only actually possible in C++, where a few
11001 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011002 } else {
John McCalle87beb22010-04-23 18:46:30 +000011003 // Use a better diagnostic if an elaborated-type-specifier
11004 // found the wrong kind of type on the first
11005 // (non-redeclaration) lookup.
11006 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11007 !Previous.isForRedeclaration()) {
11008 unsigned Kind = 0;
11009 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011010 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11011 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011012 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11013 Diag(PrevDecl->getLocation(), diag::note_declared_at);
11014 Invalid = true;
11015
11016 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000011017 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11018 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000011019 // do nothing
11020
11021 // Diagnose implicit declarations introduced by elaborated types.
11022 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11023 unsigned Kind = 0;
11024 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011025 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11026 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011027 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11028 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11029 Invalid = true;
11030
11031 // Otherwise it's a declaration. Call out a particularly common
11032 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000011033 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11034 unsigned Kind = 0;
11035 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000011036 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000011037 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000011038 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11039 Invalid = true;
11040
11041 // Otherwise, diagnose.
11042 } else {
11043 // The tag name clashes with something else in the target scope,
11044 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000011045 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000011046 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011047 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000011048 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011049 }
John McCalle87beb22010-04-23 18:46:30 +000011050
11051 // The existing declaration isn't relevant to us; we're in a
11052 // new scope, so clear out the previous declaration.
11053 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000011054 }
Chris Lattner18b19622007-01-22 07:39:13 +000011055 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000011056
Chris Lattner438e5012008-12-17 07:13:27 +000011057CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000011058
John McCall1f82f242009-11-18 22:49:29 +000011059 TagDecl *PrevDecl = 0;
11060 if (Previous.isSingleResult())
11061 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11062
Chris Lattnerbf0b7982007-01-23 04:27:41 +000011063 // If there is an identifier, use the location of the identifier as the
11064 // location of the decl, otherwise use the location of the struct/union
11065 // keyword.
11066 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000011067
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011068 // Otherwise, create a new declaration. If there is a previous
11069 // declaration of the same entity, the two will be linked via
11070 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000011071 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000011072
Douglas Gregor0bf31402010-10-08 23:50:27 +000011073 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000011074 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000011075 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11076 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011077 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000011078 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000011079 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000011080 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011081 if (TUK != TUK_Definition && !Invalid) {
11082 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000011083 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11084 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000011085 // C++0x: 7.2p2: opaque-enum-declaration.
11086 // Conflicts are diagnosed above. Do nothing.
11087 }
11088 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011089 Diag(Loc, diag::ext_forward_ref_enum_def)
11090 << New;
11091 Diag(Def->getLocation(), diag::note_previous_definition);
11092 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000011093 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000011094 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000011095 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011096 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000011097 DiagID = diag::err_forward_ref_enum;
11098 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011099
11100 // If this is a forward-declared reference to an enumeration, make a
11101 // note of it; we won't actually be introducing the declaration into
11102 // the declaration context.
11103 if (TUK == TUK_Reference)
11104 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011105 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000011106 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000011107
11108 if (EnumUnderlying) {
11109 EnumDecl *ED = cast<EnumDecl>(New);
11110 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11111 ED->setIntegerTypeSourceInfo(TI);
11112 else
11113 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11114 ED->setPromotionType(ED->getIntegerType());
11115 }
11116
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011117 } else {
11118 // struct/union/class
11119
Chris Lattner776fac82007-06-09 00:53:06 +000011120 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11121 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011122 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000011123 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011124 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011125 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011126
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011127 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000011128 StdBadAlloc = cast<CXXRecordDecl>(New);
11129 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011130 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011131 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011132 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011133
Richard Smith649c7b062014-01-08 00:56:48 +000011134 // C++11 [dcl.type]p3:
11135 // A type-specifier-seq shall not define a class or enumeration [...].
11136 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11137 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11138 << Context.getTagDeclType(New);
11139 Invalid = true;
11140 }
11141
John McCall3e11ebe2010-03-15 10:12:16 +000011142 // Maybe add qualifier info.
11143 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011144 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011145 // If this is either a declaration or a definition, check the
11146 // nested-name-specifier against the current context. We don't do this
11147 // for explicit specializations, because they have similar checking
11148 // (with more specific diagnostics) in the call to
11149 // CheckMemberSpecialization, below.
11150 if (!isExplicitSpecialization &&
11151 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11152 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11153 Invalid = true;
11154
Douglas Gregor14454802011-02-25 02:25:35 +000011155 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011156 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011157 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011158 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011159 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011160 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011161 }
11162 else
11163 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011164 }
11165
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011166 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11167 // Add alignment attributes if necessary; these attributes are checked when
11168 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011169 //
11170 // It is important for implementing the correct semantics that this
11171 // happen here (in act on tag decl). The #pragma pack stack is
11172 // maintained as a result of parser callbacks which can occur at
11173 // many points during the parsing of a struct declaration (because
11174 // the #pragma tokens are effectively skipped over during the
11175 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011176 if (TUK == TUK_Definition) {
11177 AddAlignmentAttributesForRecord(RD);
11178 AddMsStructLayoutForRecord(RD);
11179 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011180 }
11181
Douglas Gregor21823bf2011-12-20 18:11:52 +000011182 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011183 if (isExplicitSpecialization)
11184 Diag(New->getLocation(), diag::err_module_private_specialization)
11185 << 2
11186 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011187 // __module_private__ does not apply to local classes. However, we only
11188 // diagnose this as an error when the declaration specifiers are
11189 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011190 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011191 New->setModulePrivate();
11192 }
11193
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011194 // If this is a specialization of a member class (of a class template),
11195 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011196 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011197 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011198
Douglas Gregordee1be82009-01-17 00:42:38 +000011199 if (Invalid)
11200 New->setInvalidDecl();
11201
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011202 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011203 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011204
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011205 // If we're declaring or defining a tag in function prototype scope in C,
11206 // note that this type can only be used within the function and add it to
11207 // the list of decls to inject into the function definition scope.
11208 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11209 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
Douglas Gregor658b9552009-01-09 22:42:13 +000011210 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011211 DeclsInPrototypeScope.push_back(New);
11212 }
Douglas Gregor658b9552009-01-09 22:42:13 +000011213
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011214 // Set the lexical context. If the tag has a C++ scope specifier, the
11215 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011216 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011217
John McCallaa74a0c2009-08-28 07:59:38 +000011218 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011219 // In Microsoft mode, a friend declaration also acts as a forward
11220 // declaration so we always pass true to setObjectOfFriendDecl to make
11221 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011222 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011223 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11224 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011225
Anders Carlsson5558ca12009-03-26 01:19:02 +000011226 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011227 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011228 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011229
John McCall9bb74a52009-07-31 02:45:11 +000011230 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011231 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011232
Chris Lattner18b19622007-01-22 07:39:13 +000011233 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011234 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011235 // We might be replacing an existing declaration in the lookup tables;
11236 // if so, borrow its access specifier.
11237 if (PrevDecl)
11238 New->setAccess(PrevDecl->getAccess());
11239
Sebastian Redl50c68252010-08-31 00:36:30 +000011240 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011241 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011242 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011243 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11244 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011245 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011246 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011247 PushOnScopeChains(New, S, !IsForwardReference);
11248 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011249 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011250
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011251 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011252 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011253 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011254
Douglas Gregor27821ce2009-07-07 16:35:42 +000011255 // If this is the C FILE type, notify the AST context.
11256 if (IdentifierInfo *II = New->getIdentifier())
11257 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011258 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011259 II->isStr("FILE"))
11260 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011261
Rafael Espindolac67f2232012-05-10 02:50:16 +000011262 if (PrevDecl)
11263 mergeDeclAttributes(New, PrevDecl);
11264
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011265 // If there's a #pragma GCC visibility in scope, set the visibility of this
11266 // record.
11267 AddPushedVisibilityAttribute(New);
11268
Douglas Gregord6ab8742009-05-28 23:31:59 +000011269 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011270 // In C++, don't return an invalid declaration. We can't recover well from
11271 // the cases where we make the type anonymous.
11272 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011273}
Chris Lattner1300fb92007-01-23 23:42:53 +000011274
John McCall48871652010-08-21 09:40:31 +000011275void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011276 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011277 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011278
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011279 // Enter the tag context.
11280 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011281
11282 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011283
11284 // If there's a #pragma GCC visibility in scope, set the visibility of this
11285 // record.
11286 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011287}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011288
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011289Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011290 assert(isa<ObjCContainerDecl>(IDecl) &&
11291 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11292 DeclContext *OCD = cast<DeclContext>(IDecl);
11293 assert(getContainingDC(OCD) == CurContext &&
11294 "The next DeclContext should be lexically contained in the current one.");
11295 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011296 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011297}
11298
John McCall48871652010-08-21 09:40:31 +000011299void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011300 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011301 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011302 SourceLocation LBraceLoc) {
11303 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011304 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011305
John McCall1c7e6ec2009-12-20 07:58:13 +000011306 FieldCollector->StartClass();
11307
11308 if (!Record->getIdentifier())
11309 return;
11310
Anders Carlsson30f29442011-03-25 14:31:08 +000011311 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011312 Record->addAttr(new (Context)
11313 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11314
John McCall1c7e6ec2009-12-20 07:58:13 +000011315 // C++ [class]p2:
11316 // [...] The class-name is also inserted into the scope of the
11317 // class itself; this is known as the injected-class-name. For
11318 // purposes of access checking, the injected-class-name is treated
11319 // as if it were a public member name.
11320 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011321 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11322 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011323 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011324 /*PrevDecl=*/0,
11325 /*DelayTypeCreation=*/true);
11326 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011327 InjectedClassName->setImplicit();
11328 InjectedClassName->setAccess(AS_public);
11329 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11330 InjectedClassName->setDescribedClassTemplate(Template);
11331 PushOnScopeChains(InjectedClassName, S);
11332 assert(InjectedClassName->isInjectedClassName() &&
11333 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011334}
11335
John McCall48871652010-08-21 09:40:31 +000011336void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011337 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011338 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011339 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011340 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011341
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011342 // Make sure we "complete" the definition even it is invalid.
11343 if (Tag->isBeingDefined()) {
11344 assert(Tag->isInvalidDecl() && "We should already have completed it");
11345 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11346 RD->completeDefinition();
11347 }
11348
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011349 if (isa<CXXRecordDecl>(Tag))
11350 FieldCollector->FinishClass();
11351
11352 // Exit this scope of this tag's definition.
11353 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011354
11355 if (getCurLexicalContext()->isObjCContainer() &&
11356 Tag->getDeclContext()->isFileContext())
11357 Tag->setTopLevelDeclInObjCContainer();
11358
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011359 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011360 if (!Tag->isInvalidDecl())
11361 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011362}
Chris Lattner535b8302008-06-21 19:39:06 +000011363
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011364void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011365 // Exit this scope of this interface definition.
11366 PopDeclContext();
11367}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011368
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011369void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011370 assert(DC == CurContext && "Mismatch of container contexts");
11371 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011372 ActOnObjCContainerFinishDefinition();
11373}
11374
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011375void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11376 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011377 OriginalLexicalContext = 0;
11378}
11379
John McCall48871652010-08-21 09:40:31 +000011380void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011381 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011382 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011383 Tag->setInvalidDecl();
11384
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011385 // Make sure we "complete" the definition even it is invalid.
11386 if (Tag->isBeingDefined()) {
11387 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11388 RD->completeDefinition();
11389 }
11390
John McCall71ba5f22010-03-17 19:25:57 +000011391 // We're undoing ActOnTagStartDefinition here, not
11392 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11393 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011394
11395 PopDeclContext();
11396}
11397
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011398// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011399ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11400 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011401 QualType FieldTy, bool IsMsStruct,
11402 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011403 // Default to true; that shouldn't confuse checks for emptiness
11404 if (ZeroWidth)
11405 *ZeroWidth = true;
11406
Chris Lattner73bf7b42009-03-05 22:45:59 +000011407 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011408 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011409 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011410 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011411 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011412 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011413 if (FieldName)
11414 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11415 << FieldName << FieldTy << BitWidth->getSourceRange();
11416 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11417 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011418 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11419 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011420 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011421
11422 // If the bit-width is type- or value-dependent, don't try to check
11423 // it now.
11424 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011425 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011426
Anders Carlsson5df391e2008-12-06 20:33:04 +000011427 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011428 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11429 if (ICE.isInvalid())
11430 return ICE;
11431 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011432
Eli Friedmanc96d4962009-08-15 21:55:26 +000011433 if (Value != 0 && ZeroWidth)
11434 *ZeroWidth = false;
11435
Chris Lattner81ed6802008-12-12 04:56:04 +000011436 // Zero-width bitfield is ok for anonymous field.
11437 if (Value == 0 && FieldName)
11438 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011439
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011440 if (Value.isSigned() && Value.isNegative()) {
11441 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011442 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011443 << FieldName << Value.toString(10);
11444 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11445 << Value.toString(10);
11446 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011447
Douglas Gregor1efa4372009-03-11 18:59:21 +000011448 if (!FieldTy->isDependentType()) {
11449 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011450 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011451 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11452 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011453 if (FieldName)
11454 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11455 << FieldName << (unsigned)Value.getZExtValue()
11456 << (unsigned)TypeSize;
11457
11458 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11459 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11460 }
11461
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011462 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011463 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11464 << FieldName << (unsigned)Value.getZExtValue()
11465 << (unsigned)TypeSize;
11466 else
11467 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11468 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011469 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011470 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011471
Richard Smithf4c51d92012-02-04 09:53:13 +000011472 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011473}
11474
Richard Smith938f40b2011-06-11 17:19:42 +000011475/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011476/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011477Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011478 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011479 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011480 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011481 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011482 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011483}
11484
11485/// HandleField - Analyze a field of a C struct or a C++ data member.
11486///
11487FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11488 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011489 Declarator &D, Expr *BitWidth,
11490 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011491 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011492 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011493 SourceLocation Loc = DeclStart;
11494 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011495
John McCall8cb7bdf2010-06-04 23:28:52 +000011496 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11497 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011498 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011499 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011500
Douglas Gregora02a72a2010-12-15 23:18:36 +000011501 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11502 UPPC_DataMemberType)) {
11503 D.setInvalidType();
11504 T = Context.IntTy;
11505 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11506 }
11507 }
11508
Matt Arsenault376f7202013-02-26 21:16:00 +000011509 // TR 18037 does not allow fields to be declared with address spaces.
11510 if (T.getQualifiers().hasAddressSpace()) {
11511 Diag(Loc, diag::err_field_with_address_space);
11512 D.setInvalidType();
11513 }
11514
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011515 // OpenCL 1.2 spec, s6.9 r:
11516 // The event type cannot be used to declare a structure or union field.
11517 if (LangOpts.OpenCL && T->isEventT()) {
11518 Diag(Loc, diag::err_event_t_struct_field);
11519 D.setInvalidType();
11520 }
11521
Richard Smithb1402ae2013-03-18 22:52:47 +000011522 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011523
Richard Smithb4a9e862013-04-12 22:46:28 +000011524 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11525 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11526 diag::err_invalid_thread)
11527 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011528
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011529 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011530 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011531 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11532 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011533 switch (Previous.getResultKind()) {
11534 case LookupResult::Found:
11535 case LookupResult::FoundUnresolvedValue:
11536 PrevDecl = Previous.getAsSingle<NamedDecl>();
11537 break;
11538
11539 case LookupResult::FoundOverloaded:
11540 PrevDecl = Previous.getRepresentativeDecl();
11541 break;
11542
11543 case LookupResult::NotFound:
11544 case LookupResult::NotFoundInCurrentInstantiation:
11545 case LookupResult::Ambiguous:
11546 break;
11547 }
11548 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011549
11550 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11551 // Maybe we will complain about the shadowed template parameter.
11552 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11553 // Just pretend that we didn't see the previous declaration.
11554 PrevDecl = 0;
11555 }
11556
Douglas Gregor1efa4372009-03-11 18:59:21 +000011557 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11558 PrevDecl = 0;
11559
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011560 bool Mutable
11561 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011562 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011563 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011564 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011565 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011566
11567 if (NewFD->isInvalidDecl())
11568 Record->setInvalidDecl();
11569
Douglas Gregor3baa6702011-09-12 16:11:24 +000011570 if (D.getDeclSpec().isModulePrivateSpecified())
11571 NewFD->setModulePrivate();
11572
Douglas Gregor1efa4372009-03-11 18:59:21 +000011573 if (NewFD->isInvalidDecl() && PrevDecl) {
11574 // Don't introduce NewFD into scope; there's already something
11575 // with the same name in the same scope.
11576 } else if (II) {
11577 PushOnScopeChains(NewFD, S);
11578 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011579 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011580
11581 return NewFD;
11582}
11583
11584/// \brief Build a new FieldDecl and check its well-formedness.
11585///
11586/// This routine builds a new FieldDecl given the fields name, type,
11587/// record, etc. \p PrevDecl should refer to any previous declaration
11588/// with the same name and in the same scope as the field to be
11589/// created.
11590///
11591/// \returns a new FieldDecl.
11592///
Mike Stump11289f42009-09-09 15:08:12 +000011593/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011594FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011595 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011596 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011597 bool Mutable, Expr *BitWidth,
11598 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011599 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011600 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011601 Declarator *D) {
11602 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011603 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011604 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011605
Douglas Gregor1efa4372009-03-11 18:59:21 +000011606 // If we receive a broken type, recover by assuming 'int' and
11607 // marking this declaration as invalid.
11608 if (T.isNull()) {
11609 InvalidDecl = true;
11610 T = Context.IntTy;
11611 }
11612
Eli Friedmand0e8de22009-12-07 00:22:08 +000011613 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011614 if (!EltTy->isDependentType()) {
11615 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11616 // Fields of incomplete type force their record to be invalid.
11617 Record->setInvalidDecl();
11618 InvalidDecl = true;
11619 } else {
11620 NamedDecl *Def;
11621 EltTy->isIncompleteType(&Def);
11622 if (Def && Def->isInvalidDecl()) {
11623 Record->setInvalidDecl();
11624 InvalidDecl = true;
11625 }
11626 }
John McCall2677e102010-08-16 23:42:35 +000011627 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011628
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011629 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11630 if (BitWidth && getLangOpts().OpenCL) {
11631 Diag(Loc, diag::err_opencl_bitfields);
11632 InvalidDecl = true;
11633 }
11634
Steve Naroff8eeeb132007-05-08 21:09:37 +000011635 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11636 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011637 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011638 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011639 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011640
11641 TypeSourceInfo *FixedTInfo =
11642 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11643 SizeIsNegative,
11644 Oversized);
11645 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011646 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011647 TInfo = FixedTInfo;
11648 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011649 } else {
11650 if (SizeIsNegative)
11651 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011652 else if (Oversized.getBoolValue())
11653 Diag(Loc, diag::err_array_too_large)
11654 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011655 else
11656 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011657 InvalidDecl = true;
11658 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011659 }
Mike Stump11289f42009-09-09 15:08:12 +000011660
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011661 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011662 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11663 diag::err_abstract_type_in_decl,
11664 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011665 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011666
Eli Friedmanc96d4962009-08-15 21:55:26 +000011667 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011668 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011669 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011670 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11671 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011672 if (!BitWidth) {
11673 InvalidDecl = true;
11674 BitWidth = 0;
11675 ZeroWidth = false;
11676 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011677 }
Mike Stump11289f42009-09-09 15:08:12 +000011678
John McCallb1cd7da2010-06-04 08:34:12 +000011679 // Check that 'mutable' is consistent with the type of the declaration.
11680 if (!InvalidDecl && Mutable) {
11681 unsigned DiagID = 0;
11682 if (T->isReferenceType())
11683 DiagID = diag::err_mutable_reference;
11684 else if (T.isConstQualified())
11685 DiagID = diag::err_mutable_const;
11686
11687 if (DiagID) {
11688 SourceLocation ErrLoc = Loc;
11689 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11690 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11691 Diag(ErrLoc, DiagID);
11692 Mutable = false;
11693 InvalidDecl = true;
11694 }
11695 }
11696
Richard Smithab44d5b2013-12-10 08:25:00 +000011697 // C++11 [class.union]p8 (DR1460):
11698 // At most one variant member of a union may have a
11699 // brace-or-equal-initializer.
11700 if (InitStyle != ICIS_NoInit)
11701 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11702
Abramo Bagnaradff19302011-03-08 08:55:46 +000011703 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011704 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011705 if (InvalidDecl)
11706 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011707
Douglas Gregor1efa4372009-03-11 18:59:21 +000011708 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11709 Diag(Loc, diag::err_duplicate_member) << II;
11710 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11711 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011712 }
11713
David Blaikiebbafb8a2012-03-11 07:00:24 +000011714 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011715 if (Record->isUnion()) {
11716 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11717 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11718 if (RDecl->getDefinition()) {
11719 // C++ [class.union]p1: An object of a class with a non-trivial
11720 // constructor, a non-trivial copy constructor, a non-trivial
11721 // destructor, or a non-trivial copy assignment operator
11722 // cannot be a member of a union, nor can an array of such
11723 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011724 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011725 NewFD->setInvalidDecl();
11726 }
11727 }
11728
11729 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011730 // the program is ill-formed, except when compiling with MSVC extensions
11731 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011732 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011733 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11734 diag::ext_union_member_of_reference_type :
11735 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011736 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011737 if (!getLangOpts().MicrosoftExt)
11738 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011739 }
11740 }
11741 }
11742
Douglas Gregor1efa4372009-03-11 18:59:21 +000011743 // FIXME: We need to pass in the attributes given an AST
11744 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011745 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011746 // FIXME: The current scope is almost... but not entirely... correct here.
11747 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011748
Richard Smith848e1f12013-02-01 08:12:08 +000011749 if (NewFD->hasAttrs())
11750 CheckAlignasUnderalignment(NewFD);
11751 }
11752
John McCall31168b02011-06-15 23:02:42 +000011753 // In auto-retain/release, infer strong retension for fields of
11754 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011755 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011756 NewFD->setInvalidDecl();
11757
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011758 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011759 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011760
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011761 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011762 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011763}
11764
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011765bool Sema::CheckNontrivialField(FieldDecl *FD) {
11766 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011767 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011768
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011769 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11770 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011771
11772 QualType EltTy = Context.getBaseElementType(FD->getType());
11773 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011774 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011775 if (RDecl->getDefinition()) {
11776 // We check for copy constructors before constructors
11777 // because otherwise we'll never get complaints about
11778 // copy constructors.
11779
11780 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011781 // We're required to check for any non-trivial constructors. Since the
11782 // implicit default constructor is suppressed if there are any
11783 // user-declared constructors, we just need to check that there is a
11784 // trivial default constructor and a trivial copy constructor. (We don't
11785 // worry about move constructors here, since this is a C++98 check.)
11786 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011787 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011788 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011789 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011790 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011791 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011792 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011793 member = CXXDestructor;
11794
11795 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011796 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011797 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011798 // Objective-C++ ARC: it is an error to have a non-trivial field of
11799 // a union. However, system headers in Objective-C programs
11800 // occasionally have Objective-C lifetime objects within unions,
11801 // and rather than cause the program to fail, we make those
11802 // members unavailable.
11803 SourceLocation Loc = FD->getLocation();
11804 if (getSourceManager().isInSystemHeader(Loc)) {
11805 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011806 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11807 "this system field has retaining ownership",
11808 Loc));
John McCall31168b02011-06-15 23:02:42 +000011809 return false;
11810 }
11811 }
Richard Smithf720df02011-10-19 20:41:51 +000011812
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011813 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011814 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11815 diag::err_illegal_union_or_anon_struct_member)
11816 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011817 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011818 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011819 }
11820 }
11821 }
Richard Smith92f241f2012-12-08 02:53:02 +000011822
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011823 return false;
11824}
11825
Mike Stump11289f42009-09-09 15:08:12 +000011826/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011827/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011828static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011829TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011830 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011831 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011832 case tok::objc_private: return ObjCIvarDecl::Private;
11833 case tok::objc_public: return ObjCIvarDecl::Public;
11834 case tok::objc_protected: return ObjCIvarDecl::Protected;
11835 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011836 }
11837}
11838
Mike Stump11289f42009-09-09 15:08:12 +000011839/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011840/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011841Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011842 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011843 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011844 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011845
Fariborz Jahaniande615832008-04-10 23:32:45 +000011846 IdentifierInfo *II = D.getIdentifier();
11847 Expr *BitWidth = (Expr*)BitfieldWidth;
11848 SourceLocation Loc = DeclStart;
11849 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011850
Fariborz Jahaniande615832008-04-10 23:32:45 +000011851 // FIXME: Unnamed fields can be handled in various different ways, for
11852 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011853
John McCall8cb7bdf2010-06-04 23:28:52 +000011854 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11855 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011856
Fariborz Jahaniande615832008-04-10 23:32:45 +000011857 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011858 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011859 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011860 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011861 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011862 } else {
11863 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011864
Fariborz Jahaniande615832008-04-10 23:32:45 +000011865 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011866
Fariborz Jahaniande615832008-04-10 23:32:45 +000011867 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011868 if (T->isReferenceType()) {
11869 Diag(Loc, diag::err_ivar_reference_type);
11870 D.setInvalidType();
11871 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011872 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11873 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011874 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011875 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011876 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011877 }
Mike Stump11289f42009-09-09 15:08:12 +000011878
Ted Kremenek73295fa2008-07-23 18:04:17 +000011879 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011880 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011881 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11882 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011883 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011884 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011885 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11886 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011887 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011888 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011889 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011890 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011891 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011892 EnclosingContext = IMPDecl->getClassInterface();
11893 assert(EnclosingContext && "Implementation has no class interface!");
11894 }
11895 else
11896 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011897 } else {
11898 if (ObjCCategoryDecl *CDecl =
11899 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011900 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011901 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011902 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011903 }
11904 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011905 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011906 }
Mike Stump11289f42009-09-09 15:08:12 +000011907
Ted Kremenek73295fa2008-07-23 18:04:17 +000011908 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011909 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11910 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011911 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011912
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011913 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011914 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011915 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011916 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011917 && !isa<TagDecl>(PrevDecl)) {
11918 Diag(Loc, diag::err_duplicate_member) << II;
11919 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11920 NewID->setInvalidDecl();
11921 }
11922 }
11923
Ted Kremenek73295fa2008-07-23 18:04:17 +000011924 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011925 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011926
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011927 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011928 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011929
John McCall31168b02011-06-15 23:02:42 +000011930 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011931 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011932 NewID->setInvalidDecl();
11933
Douglas Gregor3baa6702011-09-12 16:11:24 +000011934 if (D.getDeclSpec().isModulePrivateSpecified())
11935 NewID->setModulePrivate();
11936
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011937 if (II) {
11938 // FIXME: When interfaces are DeclContexts, we'll need to add
11939 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011940 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011941 IdResolver.AddDecl(NewID);
11942 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011943
John McCall5fb5df92012-06-20 06:18:46 +000011944 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011945 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011946 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011947
John McCall48871652010-08-21 09:40:31 +000011948 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011949}
11950
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011951/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011952/// class and class extensions. For every class \@interface and class
11953/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011954/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011955void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011956 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011957 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011958 return;
11959
11960 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11961 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11962
Richard Smithcaf33902011-10-10 18:28:20 +000011963 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011964 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011965 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011966 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011967 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011968 if (!CD->IsClassExtension())
11969 return;
11970 }
11971 // No need to add this to end of @implementation.
11972 else
11973 return;
11974 }
11975 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011976 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11977 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011978
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011979 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011980 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011981 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011982 Context.getTrivialTypeSourceInfo(Context.CharTy,
11983 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011984 ObjCIvarDecl::Private, BW,
11985 true);
11986 AllIvarDecls.push_back(Ivar);
11987}
11988
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011989void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11990 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11991 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011992 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011993
Eric Christopher7457aaf2012-07-19 22:22:51 +000011994 // If this is an Objective-C @implementation or category and we have
11995 // new fields here we should reset the layout of the interface since
11996 // it will now change.
11997 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11998 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11999 switch (DC->getKind()) {
12000 default: break;
12001 case Decl::ObjCCategory:
12002 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12003 break;
12004 case Decl::ObjCImplementation:
12005 Context.
12006 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12007 break;
12008 }
12009 }
12010
Eli Friedmana7679412012-02-07 05:00:47 +000012011 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12012
12013 // Start counting up the number of named members; make sure to include
12014 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000012015 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000012016 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000012017 for (const auto *I : Record->decls()) {
12018 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000012019 if (IFD->getDeclName())
12020 ++NumNamedMembers;
12021 }
12022 }
12023
12024 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012025 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000012026
John McCall31168b02011-06-15 23:02:42 +000012027 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012028 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000012029 i != end; ++i) {
12030 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000012031
Chris Lattner720a0542007-01-25 00:44:24 +000012032 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000012033 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000012034
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012035 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000012036 // Remember all fields written by the user.
12037 RecFields.push_back(FD);
12038 }
Mike Stump11289f42009-09-09 15:08:12 +000012039
Chris Lattner73bf7b42009-03-05 22:45:59 +000012040 // If the field is already invalid for some reason, don't emit more
12041 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000012042 if (FD->isInvalidDecl()) {
12043 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000012044 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000012045 }
Mike Stump11289f42009-09-09 15:08:12 +000012046
Douglas Gregorac1fb652009-03-24 19:52:54 +000012047 // C99 6.7.2.1p2:
12048 // A structure or union shall not contain a member with
12049 // incomplete or function type (hence, a structure shall not
12050 // contain an instance of itself, but may contain a pointer to
12051 // an instance of itself), except that the last member of a
12052 // structure with more than one named member may have incomplete
12053 // array type; such a structure (and any union containing,
12054 // possibly recursively, a member that is such a structure)
12055 // shall not be a member of a structure or an element of an
12056 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000012057 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012058 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000012059 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012060 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000012061 FD->setInvalidDecl();
12062 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012063 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000012064 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000012065 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000012066 ((getLangOpts().MicrosoftExt ||
12067 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000012068 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012069 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000012070 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000012071 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000012072 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000012073 unsigned DiagID = 0;
12074 if (Record->isUnion())
12075 DiagID = getLangOpts().MicrosoftExt
12076 ? diag::ext_flexible_array_union_ms
12077 : getLangOpts().CPlusPlus
12078 ? diag::ext_flexible_array_union_gnu
12079 : diag::err_flexible_array_union;
12080 else if (Fields.size() == 1)
12081 DiagID = getLangOpts().MicrosoftExt
12082 ? diag::ext_flexible_array_empty_aggregate_ms
12083 : getLangOpts().CPlusPlus
12084 ? diag::ext_flexible_array_empty_aggregate_gnu
12085 : NumNamedMembers < 1
12086 ? diag::err_flexible_array_empty_aggregate
12087 : 0;
12088
12089 if (DiagID)
12090 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12091 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000012092 // While the layout of types that contain virtual bases is not specified
12093 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12094 // virtual bases after the derived members. This would make a flexible
12095 // array member declared at the end of an object not adjacent to the end
12096 // of the type.
12097 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12098 if (RD->getNumVBases() != 0)
12099 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12100 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000012101 if (!getLangOpts().C99)
12102 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12103 << FD->getDeclName() << Record->getTagKind();
12104
Richard Smith6fa28ff2014-01-11 00:53:35 +000012105 // If the element type has a non-trivial destructor, we would not
12106 // implicitly destroy the elements, so disallow it for now.
12107 //
12108 // FIXME: GCC allows this. We should probably either implicitly delete
12109 // the destructor of the containing class, or just allow this.
12110 QualType BaseElem = Context.getBaseElementType(FD->getType());
12111 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12112 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000012113 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000012114 FD->setInvalidDecl();
12115 EnclosingDecl->setInvalidDecl();
12116 continue;
12117 }
Chris Lattner720a0542007-01-25 00:44:24 +000012118 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000012119 if (Record)
12120 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000012121 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000012122 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000012123 diag::err_field_incomplete)) {
12124 // Incomplete type
12125 FD->setInvalidDecl();
12126 EnclosingDecl->setInvalidDecl();
12127 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012128 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000012129 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12130 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012131 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012132 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012133 } else {
12134 // If this is a struct/class and this is not the last element, reject
12135 // it. Note that GCC supports variable sized arrays in the middle of
12136 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012137 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012138 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012139 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012140 else {
12141 // We support flexible arrays at the end of structs in
12142 // other structs as an extension.
12143 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12144 << FD->getDeclName();
12145 if (Record)
12146 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012147 }
Chris Lattner720a0542007-01-25 00:44:24 +000012148 }
12149 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012150 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12151 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12152 diag::err_abstract_type_in_decl,
12153 AbstractIvarType)) {
12154 // Ivars can not have abstract class types
12155 FD->setInvalidDecl();
12156 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012157 if (Record && FDTTy->getDecl()->hasObjectMember())
12158 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012159 if (Record && FDTTy->getDecl()->hasVolatileMember())
12160 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012161 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012162 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012163 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12164 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12165 QualType T = Context.getObjCObjectPointerType(FD->getType());
12166 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012167 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12168 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12169 // It's an error in ARC if a field has lifetime.
12170 // We don't want to report this in a system header, though,
12171 // so we just make the field unavailable.
12172 // FIXME: that's really not sufficient; we need to make the type
12173 // itself invalid to, say, initialize or copy.
12174 QualType T = FD->getType();
12175 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12176 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12177 SourceLocation loc = FD->getLocation();
12178 if (getSourceManager().isInSystemHeader(loc)) {
12179 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012180 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12181 "this system field has retaining ownership",
12182 loc));
John McCall31168b02011-06-15 23:02:42 +000012183 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012184 } else {
12185 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012186 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012187 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012188 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012189 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012190 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012191 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012192 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012193 if (FD->getType()->isObjCObjectPointerType() ||
12194 FD->getType().isObjCGCStrong())
12195 Record->setHasObjectMember(true);
12196 else if (Context.getAsArrayType(FD->getType())) {
12197 QualType BaseType = Context.getBaseElementType(FD->getType());
12198 if (BaseType->isRecordType() &&
12199 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012200 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012201 else if (BaseType->isObjCObjectPointerType() ||
12202 BaseType.isObjCGCStrong())
12203 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012204 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012205 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012206 if (Record && FD->getType().isVolatileQualified())
12207 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012208 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012209 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012210 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012211 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012212
Chris Lattner82625602007-01-24 02:26:21 +000012213 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012214 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012215 bool Completed = false;
12216 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12217 if (!CXXRecord->isInvalidDecl()) {
12218 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012219 for (CXXRecordDecl::conversion_iterator
12220 I = CXXRecord->conversion_begin(),
12221 E = CXXRecord->conversion_end(); I != E; ++I)
12222 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012223
12224 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012225 if (CXXRecord->hasUserDeclaredDestructor()) {
12226 // Adjust user-defined destructor exception spec.
12227 if (getLangOpts().CPlusPlus11)
12228 AdjustDestructorExceptionSpec(CXXRecord,
12229 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012230 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012231
Douglas Gregor8fb95122010-09-29 00:15:42 +000012232 // Add any implicitly-declared members to this class.
12233 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12234
12235 // If we have virtual base classes, we may end up finding multiple
12236 // final overriders for a given virtual function. Check for this
12237 // problem now.
12238 if (CXXRecord->getNumVBases()) {
12239 CXXFinalOverriderMap FinalOverriders;
12240 CXXRecord->getFinalOverriders(FinalOverriders);
12241
12242 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12243 MEnd = FinalOverriders.end();
12244 M != MEnd; ++M) {
12245 for (OverridingMethods::iterator SO = M->second.begin(),
12246 SOEnd = M->second.end();
12247 SO != SOEnd; ++SO) {
12248 assert(SO->second.size() > 0 &&
12249 "Virtual function without overridding functions?");
12250 if (SO->second.size() == 1)
12251 continue;
12252
12253 // C++ [class.virtual]p2:
12254 // In a derived class, if a virtual member function of a base
12255 // class subobject has more than one final overrider the
12256 // program is ill-formed.
12257 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012258 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012259 Diag(M->first->getLocation(),
12260 diag::note_overridden_virtual_function);
12261 for (OverridingMethods::overriding_iterator
12262 OM = SO->second.begin(),
12263 OMEnd = SO->second.end();
12264 OM != OMEnd; ++OM)
12265 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012266 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012267
12268 Record->setInvalidDecl();
12269 }
12270 }
12271 CXXRecord->completeDefinition(&FinalOverriders);
12272 Completed = true;
12273 }
12274 }
12275 }
12276 }
12277
12278 if (!Completed)
12279 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012280
David Majnemer2c4e00a2014-01-29 22:07:36 +000012281 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012282 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012283
David Majnemer98c9ee22014-02-07 00:43:07 +000012284 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012285 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012286 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012287 IA->getSemanticSpelling());
12288 }
12289
Serge Pavlov3cb80222013-11-14 02:13:03 +000012290 // Check if the structure/union declaration is a type that can have zero
12291 // size in C. For C this is a language extension, for C++ it may cause
12292 // compatibility problems.
12293 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012294 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012295 CheckForZeroSize = true;
12296 } else {
12297 // For C++ filter out types that cannot be referenced in C code.
12298 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12299 CheckForZeroSize =
12300 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12301 !CXXRecord->isDependentType() &&
12302 CXXRecord->isCLike();
12303 }
12304 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012305 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012306 bool IsEmpty = true;
12307 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012308 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012309 E = Record->field_end();
12310 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12311 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012312 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012313 if (I->getBitWidthValue(Context) > 0)
12314 ZeroSize = false;
12315 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012316 ++NonBitFields;
12317 QualType FieldType = I->getType();
12318 if (FieldType->isIncompleteType() ||
12319 !Context.getTypeSizeInChars(FieldType).isZero())
12320 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012321 }
12322 }
12323
Serge Pavlov3cb80222013-11-14 02:13:03 +000012324 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12325 // allowed in C++, but warn if its declaration is inside
12326 // extern "C" block.
12327 if (ZeroSize) {
12328 Diag(RecLoc, getLangOpts().CPlusPlus ?
12329 diag::warn_zero_size_struct_union_in_extern_c :
12330 diag::warn_zero_size_struct_union_compat)
12331 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12332 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012333
Serge Pavlov3cb80222013-11-14 02:13:03 +000012334 // Structs without named members are extension in C (C99 6.7.2.1p7),
12335 // but are accepted by GCC.
12336 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12337 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12338 diag::ext_no_named_members_in_struct_union)
12339 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012340 }
12341 }
Chris Lattner622c1932008-02-06 00:51:33 +000012342 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012343 ObjCIvarDecl **ClsFields =
12344 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012345 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012346 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012347 // Add ivar's to class's DeclContext.
12348 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12349 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012350 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012351 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012352 // Must enforce the rule that ivars in the base classes may not be
12353 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012354 if (ID->getSuperClass())
12355 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012356 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012357 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012358 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012359 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12360 // Ivar declared in @implementation never belongs to the implementation.
12361 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012362 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012363 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012364 IMPDecl->setIvarLBraceLoc(LBrac);
12365 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012366 } else if (ObjCCategoryDecl *CDecl =
12367 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012368 // case of ivars in class extension; all other cases have been
12369 // reported as errors elsewhere.
12370 // FIXME. Class extension does not have a LocEnd field.
12371 // CDecl->setLocEnd(RBrac);
12372 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012373 // Diagnose redeclaration of private ivars.
12374 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012375 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012376 if (IDecl) {
12377 if (const ObjCIvarDecl *ClsIvar =
12378 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12379 Diag(ClsFields[i]->getLocation(),
12380 diag::err_duplicate_ivar_declaration);
12381 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12382 continue;
12383 }
Aaron Ballmanb4a53452014-03-13 21:57:01 +000012384 for (const auto *Ext : IDecl->known_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012385 if (const ObjCIvarDecl *ClsExtIvar
12386 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012387 Diag(ClsFields[i]->getLocation(),
12388 diag::err_duplicate_ivar_declaration);
12389 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12390 continue;
12391 }
12392 }
12393 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012394 ClsFields[i]->setLexicalDeclContext(CDecl);
12395 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012396 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012397 CDecl->setIvarLBraceLoc(LBrac);
12398 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012399 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012400 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012401
12402 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012403 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012404}
12405
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012406/// \brief Determine whether the given integral value is representable within
12407/// the given type T.
12408static bool isRepresentableIntegerValue(ASTContext &Context,
12409 llvm::APSInt &Value,
12410 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012411 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012412 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012413
Douglas Gregor0bf31402010-10-08 23:50:27 +000012414 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012415 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012416 --BitWidth;
12417 return Value.getActiveBits() <= BitWidth;
12418 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012419 return Value.getMinSignedBits() <= BitWidth;
12420}
12421
12422// \brief Given an integral type, return the next larger integral type
12423// (or a NULL type of no such type exists).
12424static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12425 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12426 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012427 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012428 const unsigned NumTypes = 4;
12429 QualType SignedIntegralTypes[NumTypes] = {
12430 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12431 };
12432 QualType UnsignedIntegralTypes[NumTypes] = {
12433 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12434 Context.UnsignedLongLongTy
12435 };
12436
12437 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012438 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12439 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012440 for (unsigned I = 0; I != NumTypes; ++I)
12441 if (Context.getTypeSize(Types[I]) > BitWidth)
12442 return Types[I];
12443
12444 return QualType();
12445}
12446
Douglas Gregor954f6b272009-03-17 19:05:46 +000012447EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12448 EnumConstantDecl *LastEnumConst,
12449 SourceLocation IdLoc,
12450 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012451 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012452 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012453 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012454 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012455
12456 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12457 Val = 0;
12458
Eli Friedman7c6515a2011-12-06 00:10:34 +000012459 if (Val)
12460 Val = DefaultLvalueConversion(Val).take();
12461
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012462 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012463 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012464 EltTy = Context.DependentTy;
12465 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012466 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012467 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012468 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012469 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12470 // constant-expression in the enumerator-definition shall be a converted
12471 // constant expression of the underlying type.
12472 EltTy = Enum->getIntegerType();
12473 ExprResult Converted =
12474 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12475 CCEK_Enumerator);
12476 if (Converted.isInvalid())
12477 Val = 0;
12478 else
12479 Val = Converted.take();
12480 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012481 !(Val = VerifyIntegerConstantExpression(Val,
12482 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012483 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012484 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012485 if (Enum->isFixed()) {
12486 EltTy = Enum->getIntegerType();
12487
Richard Smithf8379a02012-01-18 23:55:52 +000012488 // In Obj-C and Microsoft mode, require the enumeration value to be
12489 // representable in the underlying type of the enumeration. In C++11,
12490 // we perform a non-narrowing conversion as part of converted constant
12491 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012492 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012493 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012494 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012495 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012496 } else
12497 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012498 } else
John Wiegley01296292011-04-08 18:41:53 +000012499 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012500 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012501 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012502 // If the underlying type is not fixed, the type of each enumerator
12503 // is the type of its initializing value:
12504 // - If an initializer is specified for an enumerator, the
12505 // initializing value has the same type as the expression.
12506 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012507 } else {
12508 // C99 6.7.2.2p2:
12509 // The expression that defines the value of an enumeration constant
12510 // shall be an integer constant expression that has a value
12511 // representable as an int.
12512
12513 // Complain if the value is not representable in an int.
12514 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12515 Diag(IdLoc, diag::ext_enum_value_not_int)
12516 << EnumVal.toString(10) << Val->getSourceRange()
12517 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12518 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12519 // Force the type of the expression to 'int'.
12520 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12521 }
12522 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012523 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012524 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012525 }
12526 }
Mike Stump11289f42009-09-09 15:08:12 +000012527
Douglas Gregor954f6b272009-03-17 19:05:46 +000012528 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012529 if (Enum->isDependentType())
12530 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012531 else if (!LastEnumConst) {
12532 // C++0x [dcl.enum]p5:
12533 // If the underlying type is not fixed, the type of each enumerator
12534 // is the type of its initializing value:
12535 // - If no initializer is specified for the first enumerator, the
12536 // initializing value has an unspecified integral type.
12537 //
12538 // GCC uses 'int' for its unspecified integral type, as does
12539 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012540 if (Enum->isFixed()) {
12541 EltTy = Enum->getIntegerType();
12542 }
12543 else {
12544 EltTy = Context.IntTy;
12545 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012546 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012547 // Assign the last value + 1.
12548 EnumVal = LastEnumConst->getInitVal();
12549 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012550 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012551
12552 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012553 if (EnumVal < LastEnumConst->getInitVal()) {
12554 // C++0x [dcl.enum]p5:
12555 // If the underlying type is not fixed, the type of each enumerator
12556 // is the type of its initializing value:
12557 //
12558 // - Otherwise the type of the initializing value is the same as
12559 // the type of the initializing value of the preceding enumerator
12560 // unless the incremented value is not representable in that type,
12561 // in which case the type is an unspecified integral type
12562 // sufficient to contain the incremented value. If no such type
12563 // exists, the program is ill-formed.
12564 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012565 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012566 // There is no integral type larger enough to represent this
12567 // value. Complain, then allow the value to wrap around.
12568 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012569 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012570 ++EnumVal;
12571 if (Enum->isFixed())
12572 // When the underlying type is fixed, this is ill-formed.
12573 Diag(IdLoc, diag::err_enumerator_wrapped)
12574 << EnumVal.toString(10)
12575 << EltTy;
12576 else
Richard Smithfaf156a2014-03-05 22:54:58 +000012577 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000012578 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012579 } else {
12580 EltTy = T;
12581 }
12582
12583 // Retrieve the last enumerator's value, extent that type to the
12584 // type that is supposed to be large enough to represent the incremented
12585 // value, then increment.
12586 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012587 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012588 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012589 ++EnumVal;
12590
12591 // If we're not in C++, diagnose the overflow of enumerator values,
12592 // which in C99 means that the enumerator value is not representable in
12593 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12594 // permits enumerator values that are representable in some larger
12595 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012596 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012597 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012598 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012599 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12600 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12601 Diag(IdLoc, diag::ext_enum_value_not_int)
12602 << EnumVal.toString(10) << 1;
12603 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012604 }
12605 }
Mike Stump11289f42009-09-09 15:08:12 +000012606
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012607 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012608 // Make the enumerator value match the signedness and size of the
12609 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012610 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012611 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012612 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012613
Douglas Gregor954f6b272009-03-17 19:05:46 +000012614 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012615 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012616}
12617
12618
John McCall811a0f52010-10-22 23:36:17 +000012619Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12620 SourceLocation IdLoc, IdentifierInfo *Id,
12621 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012622 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012623 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012624 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012625 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012626
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012627 // The scope passed in may not be a decl scope. Zip up the scope tree until
12628 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012629 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012630
Chris Lattner8116d1b2007-01-25 22:38:29 +000012631 // Verify that there isn't already something declared with this name in this
12632 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012633 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012634 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012635 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012636 // Maybe we will complain about the shadowed template parameter.
12637 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12638 // Just pretend that we didn't see the previous declaration.
12639 PrevDecl = 0;
12640 }
12641
12642 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012643 // When in C++, we may get a TagDecl with the same name; in this case the
12644 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012645 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012646 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012647 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012648 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012649 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012650 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012651 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012652 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012653 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012654 }
12655 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012656
Aaron Ballman24a10472012-07-19 03:12:23 +000012657 // C++ [class.mem]p15:
12658 // If T is the name of a class, then each of the following shall have a name
12659 // different from T:
12660 // - every enumerator of every member of class T that is an unscoped
12661 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012662 if (CXXRecordDecl *Record
12663 = dyn_cast<CXXRecordDecl>(
12664 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012665 if (!TheEnumDecl->isScoped() &&
12666 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012667 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12668
John McCall811a0f52010-10-22 23:36:17 +000012669 EnumConstantDecl *New =
12670 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012671
John McCall553c0792010-01-23 00:46:32 +000012672 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012673 // Process attributes.
12674 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12675
12676 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012677 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012678 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012679 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012680
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012681 ActOnDocumentableDecl(New);
12682
John McCall48871652010-08-21 09:40:31 +000012683 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012684}
12685
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012686// Returns true when the enum initial expression does not trigger the
12687// duplicate enum warning. A few common cases are exempted as follows:
12688// Element2 = Element1
12689// Element2 = Element1 + 1
12690// Element2 = Element1 - 1
12691// Where Element2 and Element1 are from the same enum.
12692static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12693 Expr *InitExpr = ECD->getInitExpr();
12694 if (!InitExpr)
12695 return true;
12696 InitExpr = InitExpr->IgnoreImpCasts();
12697
12698 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12699 if (!BO->isAdditiveOp())
12700 return true;
12701 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12702 if (!IL)
12703 return true;
12704 if (IL->getValue() != 1)
12705 return true;
12706
12707 InitExpr = BO->getLHS();
12708 }
12709
12710 // This checks if the elements are from the same enum.
12711 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12712 if (!DRE)
12713 return true;
12714
12715 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12716 if (!EnumConstant)
12717 return true;
12718
12719 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12720 Enum)
12721 return true;
12722
12723 return false;
12724}
12725
12726struct DupKey {
12727 int64_t val;
12728 bool isTombstoneOrEmptyKey;
12729 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12730 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12731};
12732
12733static DupKey GetDupKey(const llvm::APSInt& Val) {
12734 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12735 false);
12736}
12737
12738struct DenseMapInfoDupKey {
12739 static DupKey getEmptyKey() { return DupKey(0, true); }
12740 static DupKey getTombstoneKey() { return DupKey(1, true); }
12741 static unsigned getHashValue(const DupKey Key) {
12742 return (unsigned)(Key.val * 37);
12743 }
12744 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12745 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12746 LHS.val == RHS.val;
12747 }
12748};
12749
12750// Emits a warning when an element is implicitly set a value that
12751// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012752static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12753 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012754 QualType EnumType) {
12755 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12756 Enum->getLocation()) ==
12757 DiagnosticsEngine::Ignored)
12758 return;
12759 // Avoid anonymous enums
12760 if (!Enum->getIdentifier())
12761 return;
12762
12763 // Only check for small enums.
12764 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12765 return;
12766
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012767 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12768 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012769
12770 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12771 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12772 ValueToVectorMap;
12773
12774 DuplicatesVector DupVector;
12775 ValueToVectorMap EnumMap;
12776
12777 // Populate the EnumMap with all values represented by enum constants without
12778 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012779 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012780 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012781
12782 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12783 // this constant. Skip this enum since it may be ill-formed.
12784 if (!ECD) {
12785 return;
12786 }
12787
12788 if (ECD->getInitExpr())
12789 continue;
12790
12791 DupKey Key = GetDupKey(ECD->getInitVal());
12792 DeclOrVector &Entry = EnumMap[Key];
12793
12794 // First time encountering this value.
12795 if (Entry.isNull())
12796 Entry = ECD;
12797 }
12798
12799 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012800 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012801 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12802 if (!ValidDuplicateEnum(ECD, Enum))
12803 continue;
12804
12805 DupKey Key = GetDupKey(ECD->getInitVal());
12806
12807 DeclOrVector& Entry = EnumMap[Key];
12808 if (Entry.isNull())
12809 continue;
12810
12811 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12812 // Ensure constants are different.
12813 if (D == ECD)
12814 continue;
12815
12816 // Create new vector and push values onto it.
12817 ECDVector *Vec = new ECDVector();
12818 Vec->push_back(D);
12819 Vec->push_back(ECD);
12820
12821 // Update entry to point to the duplicates vector.
12822 Entry = Vec;
12823
12824 // Store the vector somewhere we can consult later for quick emission of
12825 // diagnostics.
12826 DupVector.push_back(Vec);
12827 continue;
12828 }
12829
12830 ECDVector *Vec = Entry.get<ECDVector*>();
12831 // Make sure constants are not added more than once.
12832 if (*Vec->begin() == ECD)
12833 continue;
12834
12835 Vec->push_back(ECD);
12836 }
12837
12838 // Emit diagnostics.
12839 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12840 DupVectorEnd = DupVector.end();
12841 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12842 ECDVector *Vec = *DupVectorIter;
12843 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12844
12845 // Emit warning for one enum constant.
12846 ECDVector::iterator I = Vec->begin();
12847 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12848 << (*I)->getName() << (*I)->getInitVal().toString(10)
12849 << (*I)->getSourceRange();
12850 ++I;
12851
12852 // Emit one note for each of the remaining enum constants with
12853 // the same value.
12854 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12855 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12856 << (*I)->getName() << (*I)->getInitVal().toString(10)
12857 << (*I)->getSourceRange();
12858 delete Vec;
12859 }
12860}
12861
Mike Stump6814d1c2009-05-16 07:06:02 +000012862void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012863 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012864 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012865 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012866 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012867 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012868
12869 if (Attr)
12870 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012871
Eli Friedmand0e60972009-12-11 01:34:50 +000012872 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012873 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012874 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012875 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012876 if (!ECD) continue;
12877
12878 ECD->setType(EnumType);
12879 }
12880
John McCall9aa35be2010-05-06 08:49:23 +000012881 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012882 return;
12883 }
12884
Chris Lattner67933c02007-08-28 05:10:31 +000012885 // TODO: If the result value doesn't fit in an int, it must be a long or long
12886 // long value. ISO C does not support this, but GCC does as an extension,
12887 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012888 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12889 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12890 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012891
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012892 // Verify that all the values are okay, compute the size of the values, and
12893 // reverse the list.
12894 unsigned NumNegativeBits = 0;
12895 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012896
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012897 // Keep track of whether all elements have type int.
12898 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012899
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012900 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012901 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012902 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012903 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012904
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012905 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012906
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012907 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012908 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012909 NumPositiveBits = std::max(NumPositiveBits,
12910 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012911 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012912 NumNegativeBits = std::max(NumNegativeBits,
12913 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012914
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012915 // Keep track of whether every enum element has type int (very commmon).
12916 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012917 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012918 }
Mike Stump11289f42009-09-09 15:08:12 +000012919
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012920 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012921 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012922 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012923
John McCall56774992009-12-09 09:09:27 +000012924 // C++0x N3000 [conv.prom]p3:
12925 // An rvalue of an unscoped enumeration type whose underlying
12926 // type is not fixed can be converted to an rvalue of the first
12927 // of the following types that can represent all the values of
12928 // the enumeration: int, unsigned int, long int, unsigned long
12929 // int, long long int, or unsigned long long int.
12930 // C99 6.4.4.3p2:
12931 // An identifier declared as an enumeration constant has type int.
12932 // The C99 rule is modified by a gcc extension
12933 QualType BestPromotionType;
12934
Aaron Ballman9ead1242013-12-19 02:39:40 +000012935 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012936 // -fshort-enums is the equivalent to specifying the packed attribute on all
12937 // enum definitions.
12938 if (LangOpts.ShortEnums)
12939 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012940
Douglas Gregor0bf31402010-10-08 23:50:27 +000012941 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012942 BestType = Enum->getIntegerType();
12943 if (BestType->isPromotableIntegerType())
12944 BestPromotionType = Context.getPromotedIntegerType(BestType);
12945 else
12946 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012947 // We don't need to set BestWidth, because BestType is going to be the type
12948 // of the enumerators, but we do anyway because otherwise some compilers
12949 // warn that it might be used uninitialized.
12950 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012951 }
12952 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012953 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012954 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012955 // If it's packed, check also if it fits a char or a short.
12956 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012957 BestType = Context.SignedCharTy;
12958 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012959 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012960 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012961 BestType = Context.ShortTy;
12962 BestWidth = ShortWidth;
12963 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012964 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012965 BestWidth = IntWidth;
12966 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012967 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012968
John McCall56774992009-12-09 09:09:27 +000012969 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012970 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012971 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012972 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012973
Chris Lattner3a370bf2007-08-29 17:31:48 +000012974 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000012975 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012976 BestType = Context.LongLongTy;
12977 }
12978 }
John McCall56774992009-12-09 09:09:27 +000012979 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012980 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012981 // If there is no negative value, figure out the smallest type that fits
12982 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012983 // If it's packed, check also if it fits a char or a short.
12984 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012985 BestType = Context.UnsignedCharTy;
12986 BestPromotionType = Context.IntTy;
12987 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012988 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012989 BestType = Context.UnsignedShortTy;
12990 BestPromotionType = Context.IntTy;
12991 BestWidth = ShortWidth;
12992 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012993 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012994 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012995 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012996 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012997 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012998 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012999 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013000 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013001 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013002 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013003 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000013004 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013005 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013006 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013007 "How could an initializer get larger than ULL?");
13008 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013009 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013010 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013011 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013012 }
13013 }
Mike Stump11289f42009-09-09 15:08:12 +000013014
Chris Lattner3a370bf2007-08-29 17:31:48 +000013015 // Loop over all of the enumerator constants, changing their types to match
13016 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013017 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000013018 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013019 if (!ECD) continue; // Already issued a diagnostic.
13020
13021 // Standard C says the enumerators have int type, but we allow, as an
13022 // extension, the enumerators to be larger than int size. If each
13023 // enumerator value fits in an int, type it as an int, otherwise type it the
13024 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
13025 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000013026
13027 // Determine whether the value fits into an int.
13028 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013029
13030 // If it fits into an integer type, force it. Otherwise force it to match
13031 // the enum decl type.
13032 QualType NewTy;
13033 unsigned NewWidth;
13034 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000013035 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000013036 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013037 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000013038 NewTy = Context.IntTy;
13039 NewWidth = IntWidth;
13040 NewSign = true;
13041 } else if (ECD->getType() == BestType) {
13042 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000013043 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013044 // C++ [dcl.enum]p4: Following the closing brace of an
13045 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013046 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013047 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013048 continue;
13049 } else {
13050 NewTy = BestType;
13051 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013052 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013053 }
13054
13055 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000013056 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013057 InitVal.setIsSigned(NewSign);
13058 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000013059
Chris Lattner3a370bf2007-08-29 17:31:48 +000013060 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000013061 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000013062 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000013063 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000013064 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000013065 ECD->getInitExpr(),
13066 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000013067 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000013068 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013069 // C++ [dcl.enum]p4: Following the closing brace of an
13070 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013071 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013072 ECD->setType(EnumType);
13073 else
13074 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013075 }
Mike Stump11289f42009-09-09 15:08:12 +000013076
John McCall9aa35be2010-05-06 08:49:23 +000013077 Enum->completeDefinition(BestType, BestPromotionType,
13078 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000013079
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013080 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000013081
13082 // Now that the enum type is defined, ensure it's not been underaligned.
13083 if (Enum->hasAttrs())
13084 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013085}
Chris Lattner1300fb92007-01-23 23:42:53 +000013086
Abramo Bagnara348823a2011-03-03 14:20:18 +000013087Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13088 SourceLocation StartLoc,
13089 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000013090 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000013091
Douglas Gregor278f52e2009-05-30 00:08:05 +000013092 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000013093 AsmString, StartLoc,
13094 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013095 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000013096 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000013097}
Eli Friedman5ed51982009-06-05 02:44:36 +000013098
Richard Smith77944862014-03-02 05:58:18 +000013099static void checkModuleImportContext(Sema &S, Module *M,
13100 SourceLocation ImportLoc,
13101 DeclContext *DC) {
13102 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13103 switch (LSD->getLanguage()) {
13104 case LinkageSpecDecl::lang_c:
13105 if (!M->IsExternC) {
13106 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13107 << M->getFullModuleName();
13108 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13109 return;
13110 }
13111 break;
13112 case LinkageSpecDecl::lang_cxx:
13113 break;
13114 }
13115 DC = LSD->getParent();
13116 }
13117
13118 while (isa<LinkageSpecDecl>(DC))
13119 DC = DC->getParent();
13120 if (!isa<TranslationUnitDecl>(DC)) {
13121 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13122 << M->getFullModuleName() << DC;
13123 S.Diag(cast<Decl>(DC)->getLocStart(),
13124 diag::note_module_import_not_at_top_level)
13125 << DC;
13126 }
13127}
13128
Douglas Gregor22d09742012-01-03 18:04:46 +000013129DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13130 SourceLocation ImportLoc,
13131 ModuleIdPath Path) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000013132 Module *Mod =
13133 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13134 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013135 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013136 return true;
Richard Smith77944862014-03-02 05:58:18 +000013137
13138 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13139
Ben Langmuir527040e2014-05-05 05:31:33 +000013140 // FIXME: we should support importing a submodule within a different submodule
13141 // of the same top-level module. Until we do, make it an error rather than
13142 // silently ignoring the import.
13143 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13144 Diag(ImportLoc, diag::err_module_self_import)
13145 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13146
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013147 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013148 Module *ModCheck = Mod;
13149 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13150 // If we've run out of module parents, just drop the remaining identifiers.
13151 // We need the length to be consistent.
13152 if (!ModCheck)
13153 break;
13154 ModCheck = ModCheck->Parent;
13155
13156 IdentifierLocs.push_back(Path[I].second);
13157 }
13158
13159 ImportDecl *Import = ImportDecl::Create(Context,
13160 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013161 AtLoc.isValid()? AtLoc : ImportLoc,
13162 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013163 Context.getTranslationUnitDecl()->addDecl(Import);
13164 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013165}
13166
Richard Smithce587f52013-11-15 04:24:58 +000013167void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013168 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13169
Richard Smithce587f52013-11-15 04:24:58 +000013170 // FIXME: Should we synthesize an ImportDecl here?
Alp Tokerb6cc5922014-05-03 03:45:55 +000013171 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13172 /*Complain=*/true);
Richard Smithce587f52013-11-15 04:24:58 +000013173}
13174
Richard Smith3d23c422014-05-07 02:25:43 +000013175void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13176 Module *Mod) {
13177 // Bail if we're not allowed to implicitly import a module here.
13178 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13179 return;
13180
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013181 // Create the implicit import declaration.
13182 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13183 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13184 Loc, Mod, Loc);
13185 TU->addDecl(ImportD);
13186 Consumer.HandleImplicitImportDecl(ImportD);
13187
13188 // Make the module visible.
Alp Tokerb6cc5922014-05-03 03:45:55 +000013189 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13190 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013191}
13192
David Chisnall0867d9c2012-02-18 16:12:34 +000013193void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13194 IdentifierInfo* AliasName,
13195 SourceLocation PragmaLoc,
13196 SourceLocation NameLoc,
13197 SourceLocation AliasNameLoc) {
13198 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13199 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013200 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13201 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013202
13203 if (PrevDecl)
13204 PrevDecl->addAttr(Attr);
13205 else
13206 (void)ExtnameUndeclaredIdentifiers.insert(
13207 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13208}
13209
Eli Friedman5ed51982009-06-05 02:44:36 +000013210void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13211 SourceLocation PragmaLoc,
13212 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013213 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013214
Eli Friedman5ed51982009-06-05 02:44:36 +000013215 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013216 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013217 } else {
13218 (void)WeakUndeclaredIdentifiers.insert(
13219 std::pair<IdentifierInfo*,WeakInfo>
13220 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013221 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013222}
13223
13224void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13225 IdentifierInfo* AliasName,
13226 SourceLocation PragmaLoc,
13227 SourceLocation NameLoc,
13228 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013229 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13230 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013231 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013232
Eli Friedman5ed51982009-06-05 02:44:36 +000013233 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013234 if (!PrevDecl->hasAttr<AliasAttr>())
13235 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013236 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013237 } else {
13238 (void)WeakUndeclaredIdentifiers.insert(
13239 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013240 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013241}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013242
13243Decl *Sema::getObjCDeclContext() const {
13244 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13245}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013246
13247AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013248 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013249 // If we are within an Objective-C method, we should consult
13250 // both the availability of the method as well as the
13251 // enclosing class. If the class is (say) deprecated,
13252 // the entire method is considered deprecated from the
13253 // purpose of checking if the current context is deprecated.
13254 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13255 AvailabilityResult R = MD->getAvailability();
13256 if (R != AR_Available)
13257 return R;
13258 D = MD->getClassInterface();
13259 }
13260 // If we are within an Objective-c @implementation, it
13261 // gets the same availability context as the @interface.
13262 else if (const ObjCImplementationDecl *ID =
13263 dyn_cast<ObjCImplementationDecl>(D)) {
13264 D = ID->getClassInterface();
13265 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013266 return D->getAvailability();
13267}