blob: 71017f4f9dfe6f6ac8a9462093a07e805e990ced [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
Reid Kleckner1ba38f82014-07-08 20:05:48 +0000131static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
132 const IdentifierInfo &II,
133 SourceLocation NameLoc) {
Reid Klecknerfd068272014-07-08 21:35:03 +0000134 // Find the first parent class template context, if any.
135 // FIXME: Perform the lookup in all enclosing class templates.
136 const CXXRecordDecl *RD = nullptr;
137 for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) {
138 RD = dyn_cast<CXXRecordDecl>(DC);
139 if (RD && RD->getDescribedClassTemplate())
140 break;
141 }
142 if (!RD)
Reid Kleckner1ba38f82014-07-08 20:05:48 +0000143 return ParsedType();
144
145 // Look for type decls in dependent base classes that have known primary
146 // templates.
147 bool FoundTypeDecl = false;
148 for (const auto &Base : RD->bases()) {
149 auto *TST = Base.getType()->getAs<TemplateSpecializationType>();
150 if (!TST || !TST->isDependentType())
151 continue;
152 auto *TD = TST->getTemplateName().getAsTemplateDecl();
153 if (!TD)
154 continue;
Nikola Smiljanic92516a82014-08-24 23:28:47 +0000155 auto *BasePrimaryTemplate =
156 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
157 if (!BasePrimaryTemplate)
158 continue;
Reid Klecknerfd068272014-07-08 21:35:03 +0000159 // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly
160 // by calling or integrating with the main LookupQualifiedName mechanism.
Reid Kleckner1ba38f82014-07-08 20:05:48 +0000161 for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) {
162 if (FoundTypeDecl)
163 return ParsedType();
164 FoundTypeDecl = isa<TypeDecl>(ND);
165 if (!FoundTypeDecl)
166 return ParsedType();
167 }
168 }
169 if (!FoundTypeDecl)
170 return ParsedType();
171
172 // We found some types in dependent base classes. Recover as if the user
173 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
174 // lookup during template instantiation.
175 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
176
177 ASTContext &Context = S.Context;
178 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
179 cast<Type>(Context.getRecordType(RD)));
180 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
181
182 CXXScopeSpec SS;
183 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
184
185 TypeLocBuilder Builder;
186 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
187 DepTL.setNameLoc(NameLoc);
188 DepTL.setElaboratedKeywordLoc(SourceLocation());
189 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
190 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
191}
192
Douglas Gregorec6e1892009-02-04 19:16:12 +0000193/// \brief If the identifier refers to a type name within this scope,
194/// return the declaration of that type.
195///
196/// This routine performs ordinary name lookup of the identifier II
197/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000198/// determine whether the name refers to a type. If so, returns an
199/// opaque pointer (actually a QualType) corresponding to that
200/// type. Otherwise, returns NULL.
Dmitri Gribenko5267fdf2013-05-03 13:12:11 +0000201ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000202 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000203 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000204 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000205 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000206 bool WantNontrivialTypeSourceInfo,
207 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000208 // Determine where we will perform name lookup.
Craig Topperc3ec1492014-05-26 06:22:03 +0000209 DeclContext *LookupCtx = nullptr;
Douglas Gregora25d65d2009-11-20 22:03:38 +0000210 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000211 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000212 if (ObjectType->isRecordType())
213 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000214 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000215 LookupCtx = computeDeclContext(*SS, false);
216
217 if (!LookupCtx) {
218 if (isDependentScopeSpecifier(*SS)) {
219 // C++ [temp.res]p3:
220 // A qualified-id that refers to a type and in which the
221 // nested-name-specifier depends on a template-parameter (14.6.2)
222 // shall be prefixed by the keyword typename to indicate that the
223 // qualified-id denotes a type, forming an
224 // elaborated-type-specifier (7.1.5.3).
225 //
226 // We therefore do not perform any name lookup if the result would
227 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000228 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000229 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000230
John McCallc392f372010-06-11 00:33:02 +0000231 // We know from the grammar that this name refers to a type,
232 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000233 if (WantNontrivialTypeSourceInfo)
234 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
235
236 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
Nico Weberdfc59202014-05-03 22:07:35 +0000237 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
238 II, NameLoc);
239 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000240 }
241
John McCallba7bf592010-08-24 05:47:05 +0000242 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000243 }
244
John McCall0b66eb32010-05-01 00:40:08 +0000245 if (!LookupCtx->isDependentContext() &&
246 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000247 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000248 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000249
250 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
251 // lookup for class-names.
252 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
253 LookupOrdinaryName;
254 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000255 if (LookupCtx) {
256 // Perform "qualified" name lookup into the declaration context we
257 // computed, which is either the type of the base of a member access
258 // expression or the declaration context associated with a prior
259 // nested-name-specifier.
260 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000261
Douglas Gregora25d65d2009-11-20 22:03:38 +0000262 if (ObjectTypePtr && Result.empty()) {
263 // C++ [basic.lookup.classref]p3:
264 // If the unqualified-id is ~type-name, the type-name is looked up
265 // in the context of the entire postfix-expression. If the type T of
266 // the object expression is of a class type C, the type-name is also
267 // looked up in the scope of class C. At least one of the lookups shall
268 // find a name that refers to (possibly cv-qualified) T.
269 LookupName(Result, S);
270 }
271 } else {
272 // Perform unqualified name lookup.
273 LookupName(Result, S);
Reid Kleckner1ba38f82014-07-08 20:05:48 +0000274
275 // For unqualified lookup in a class template in MSVC mode, look into
276 // dependent base classes where the primary class template is known.
277 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
278 if (ParsedType TypeInBase =
279 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
280 return TypeInBase;
281 }
Douglas Gregora25d65d2009-11-20 22:03:38 +0000282 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000283
284 NamedDecl *IIDecl = nullptr;
John McCall27b18f82009-11-17 02:14:36 +0000285 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000286 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000287 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000288 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000289 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000290 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +0000291 Kind, S, SS, Validator,
292 CTK_ErrorRecovery);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000293 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
294 TemplateTy Template;
295 bool MemberOfUnknownSpecialization;
296 UnqualifiedId TemplateName;
297 TemplateName.setIdentifier(NewII, NameLoc);
298 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
299 CXXScopeSpec NewSS, *NewSSPtr = SS;
300 if (SS && NNS) {
301 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
302 NewSSPtr = &NewSS;
303 }
304 if (Correction && (NNS || NewII != &II) &&
305 // Ignore a correction to a template type as the to-be-corrected
306 // identifier is not a template (typo correction for template names
307 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000309 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
310 false, Template, MemberOfUnknownSpecialization))) {
311 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
312 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000313 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000314 WantNontrivialTypeSourceInfo);
315 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000316 diagnoseTypo(Correction,
317 PDiag(diag::err_unknown_type_or_class_name_suggest)
318 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000319 if (SS && NNS)
320 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
321 *CorrectedII = NewII;
322 return Ty;
323 }
324 }
325 }
326 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000327 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000328 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000329 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000330 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000331
Chris Lattnere40853a2009-10-25 22:09:09 +0000332 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000333 // Recover from type-hiding ambiguities by hiding the type. We'll
334 // do the lookup again when looking for an object, and we can
335 // diagnose the error then. If we don't do this, then the error
336 // about hiding the type will be immediately followed by an error
337 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000338 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
339 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000340 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000341 }
John McCall6538c932009-10-10 05:48:19 +0000342
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000343 // Look to see if we have a type anywhere in the list of results.
344 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
345 Res != ResEnd; ++Res) {
346 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000347 if (!IIDecl ||
348 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000349 IIDecl->getLocation().getRawEncoding())
350 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000351 }
352 }
353
354 if (!IIDecl) {
355 // None of the entities we found is a type, so there is no way
356 // to even assume that the result is a type. In this case, don't
357 // complain about the ambiguity. The parser will either try to
358 // perform this lookup again (e.g., as an object name), which
359 // will produce the ambiguity, or will complain that it expected
360 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000361 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000362 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000363 }
364
365 // We found a type within the ambiguous lookup; diagnose the
366 // ambiguity and then return that type. This might be the right
367 // answer, or it might not be, but it suppresses any attempt to
368 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000369 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000370
Chris Lattnera3778332009-02-16 22:07:16 +0000371 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000372 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000373 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000374 }
375
Chris Lattner17e15f12009-10-25 17:16:46 +0000376 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000377
Chris Lattner17e15f12009-10-25 17:16:46 +0000378 QualType T;
379 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000380 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000381
Nico Weberdfc59202014-05-03 22:07:35 +0000382 T = Context.getTypeDeclType(TD);
Nico Weber72889432014-09-06 01:25:55 +0000383 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Abramo Bagnara4244b432012-01-27 08:46:19 +0000384
385 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
386 // constructor or destructor name (in such a case, the scope specifier
387 // will be attached to the enclosing Expr or Decl node).
388 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor844cb502011-03-01 18:12:44 +0000389 if (WantNontrivialTypeSourceInfo) {
390 // Construct a type with type-source information.
391 TypeLocBuilder Builder;
392 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
393
394 T = getElaboratedType(ETK_None, *SS, T);
395 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000396 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-03-01 18:12:44 +0000397 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
398 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
399 } else {
400 T = getElaboratedType(ETK_None, *SS, T);
401 }
402 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000403 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000404 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000405 if (!HasTrailingDot)
406 T = Context.getObjCInterfaceType(IDecl);
407 }
408
409 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000410 // If it's not plausibly a type, suppress diagnostics.
411 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000412 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000413 }
John McCallba7bf592010-08-24 05:47:05 +0000414 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000415}
416
Reid Klecknerdf6e4a02014-06-06 22:36:36 +0000417// Builds a fake NNS for the given decl context.
418static NestedNameSpecifier *
419synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
420 for (;; DC = DC->getLookupParent()) {
421 DC = DC->getPrimaryContext();
422 auto *ND = dyn_cast<NamespaceDecl>(DC);
423 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
424 return NestedNameSpecifier::Create(Context, nullptr, ND);
425 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
426 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
427 RD->getTypeForDecl());
428 else if (isa<TranslationUnitDecl>(DC))
429 return NestedNameSpecifier::GlobalSpecifier(Context);
430 }
431 llvm_unreachable("something isn't in TU scope?");
432}
433
434ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
435 SourceLocation NameLoc) {
436 // Accepting an undeclared identifier as a default argument for a template
437 // type parameter is a Microsoft extension.
438 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
439
440 // Build a fake DependentNameType that will perform lookup into CurContext at
441 // instantiation time. The name specifier isn't dependent, so template
442 // instantiation won't transform it. It will retry the lookup, however.
443 NestedNameSpecifier *NNS =
444 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
445 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
446
447 // Build type location information. We synthesized the qualifier, so we have
448 // to build a fake NestedNameSpecifierLoc.
449 NestedNameSpecifierLocBuilder NNSLocBuilder;
450 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
451 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
452
453 TypeLocBuilder Builder;
454 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
455 DepTL.setNameLoc(NameLoc);
456 DepTL.setElaboratedKeywordLoc(SourceLocation());
457 DepTL.setQualifierLoc(QualifierLoc);
458 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
459}
460
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000461/// isTagName() - This method is called *for error recovery purposes only*
462/// to determine if the specified name is a valid tag name ("struct foo"). If
463/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matosdc86f942012-08-31 18:45:21 +0000464/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
465/// cases in C where the user forgot to specify the tag.
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000466DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
467 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000468 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
469 LookupName(R, S, false);
470 R.suppressDiagnostics();
471 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000472 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000473 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000474 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000475 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-05-11 21:36:43 +0000476 case TTK_Union: return DeclSpec::TST_union;
477 case TTK_Class: return DeclSpec::TST_class;
478 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000479 }
480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000482 return DeclSpec::TST_unspecified;
483}
484
Francois Pichet48c946e2011-04-13 02:38:49 +0000485/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
486/// if a CXXScopeSpec's type is equal to the type of one of the base classes
487/// then downgrade the missing typename error to a warning.
488/// This is needed for MSVC compatibility; Example:
489/// @code
490/// template<class T> class A {
491/// public:
492/// typedef int TYPE;
493/// };
494/// template<class T> class B : public A<T> {
495/// public:
496/// A<T>::TYPE a; // no typename required because A<T> is a base class.
497/// };
498/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000499bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000500 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000501 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000502
503 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
Aaron Ballman574705e2014-03-13 15:41:46 +0000504 for (const auto &Base : RD->bases())
505 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
Francois Pichet48c946e2011-04-13 02:38:49 +0000506 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000507 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000508 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000509 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000510}
511
Reid Klecknerc05ca5e2014-06-19 01:23:22 +0000512void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000513 SourceLocation IILoc,
514 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000515 CXXScopeSpec *SS,
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000516 ParsedType &SuggestedType,
517 bool AllowClassTemplates) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000518 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000519 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000520
Douglas Gregor2d435302009-12-30 17:04:44 +0000521 // There may have been a typo in the name of the type. Look up typo
522 // results, in case we have something that we can suggest.
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000523 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000524 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000525 LookupOrdinaryName, S, SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000526 Validator, CTK_ErrorRecovery)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000527 if (Corrected.isKeyword()) {
528 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000529 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
530 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000531 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000532 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000533 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000534 diagnoseTypo(Corrected,
535 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000536 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000537 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
538 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000539 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000540 diagnoseTypo(Corrected,
541 PDiag(diag::err_unknown_nested_typename_suggest)
542 << II << DC << DroppedSpecifier << SS->getRange());
543 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000544 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000545 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000546
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000547 CXXScopeSpec tmpSS;
548 if (Corrected.getCorrectionSpecifier())
549 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
550 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000551 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000552 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
553 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000554 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000555 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000556 }
Reid Klecknerc05ca5e2014-06-19 01:23:22 +0000557 return;
Douglas Gregor2d435302009-12-30 17:04:44 +0000558 }
559
David Blaikiebbafb8a2012-03-11 07:00:24 +0000560 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000561 // See if II is a class template that the user forgot to pass arguments to.
562 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000563 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000564 CXXScopeSpec EmptySS;
565 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000566 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000567 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000568 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000569 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000570 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000571 Diag(IILoc, diag::err_template_missing_args) << TplName;
572 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
573 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
574 << TplDecl->getTemplateParameters()->getSourceRange();
575 }
Reid Klecknerc05ca5e2014-06-19 01:23:22 +0000576 return;
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000577 }
578 }
579
Douglas Gregor15e56022009-10-13 23:27:22 +0000580 // FIXME: Should we move the logic that tries to recover from a missing tag
581 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
582
Douglas Gregor2d435302009-12-30 17:04:44 +0000583 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000584 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000585 else if (DeclContext *DC = computeDeclContext(*SS, false))
586 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000587 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000588 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000589 unsigned DiagID = diag::err_typename_missing;
Alp Tokerbfa39342014-01-14 12:51:41 +0000590 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Reid Kleckner32506ed2014-06-12 23:03:48 +0000591 DiagID = diag::ext_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000592
593 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000594 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000595 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000596 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000597 SuggestedType = ActOnTypenameType(S, SourceLocation(),
598 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000599 } else {
600 assert(SS && SS->isInvalid() &&
601 "Invalid scope specifier has already been diagnosed");
602 }
Douglas Gregor15e56022009-10-13 23:27:22 +0000603}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000604
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000605/// \brief Determine whether the given result set contains either a type name
606/// or
607static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000608 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000609 NextToken.is(tok::less);
610
611 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
612 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
613 return true;
614
615 if (CheckTemplate && isa<TemplateDecl>(*I))
616 return true;
617 }
618
619 return false;
620}
621
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000622static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
623 Scope *S, CXXScopeSpec &SS,
624 IdentifierInfo *&Name,
625 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000626 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
627 SemaRef.LookupParsedName(R, S, &SS);
628 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Alp Toker68837432014-05-20 22:03:47 +0000629 StringRef FixItTagName;
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000630 switch (Tag->getTagKind()) {
631 case TTK_Class:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000632 FixItTagName = "class ";
633 break;
634
635 case TTK_Enum:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000636 FixItTagName = "enum ";
637 break;
638
639 case TTK_Struct:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000640 FixItTagName = "struct ";
641 break;
642
Joao Matosdc86f942012-08-31 18:45:21 +0000643 case TTK_Interface:
Joao Matosdc86f942012-08-31 18:45:21 +0000644 FixItTagName = "__interface ";
645 break;
646
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000647 case TTK_Union:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000648 FixItTagName = "union ";
649 break;
650 }
651
Alp Toker68837432014-05-20 22:03:47 +0000652 StringRef TagName = FixItTagName.drop_back();
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000653 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
654 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
655 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
656
Richard Smithaa31b4b2012-09-06 01:37:56 +0000657 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
658 I != IEnd; ++I)
659 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
660 << Name << TagName;
661
662 // Replace lookup results with just the tag decl.
663 Result.clear(Sema::LookupTagName);
664 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000665 return true;
666 }
667
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000668 return false;
669}
670
Richard Smith4f605af2012-08-18 00:55:03 +0000671/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
672static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
673 QualType T, SourceLocation NameLoc) {
674 ASTContext &Context = S.Context;
675
676 TypeLocBuilder Builder;
677 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
678
679 T = S.getElaboratedType(ETK_None, SS, T);
680 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
681 ElabTL.setElaboratedKeywordLoc(SourceLocation());
682 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
683 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
684}
685
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000686Sema::NameClassification Sema::ClassifyName(Scope *S,
687 CXXScopeSpec &SS,
688 IdentifierInfo *&Name,
689 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000690 const Token &NextToken,
691 bool IsAddressOfOperand,
692 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000693 DeclarationNameInfo NameInfo(Name, NameLoc);
694 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000695
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000696 if (NextToken.is(tok::coloncolon)) {
697 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000698 QualType(), false, SS, nullptr, false);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000699 }
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000700
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000701 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
702 LookupParsedName(Result, S, &SS, !CurMethod);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000703
Reid Kleckner1ba38f82014-07-08 20:05:48 +0000704 // For unqualified lookup in a class template in MSVC mode, look into
705 // dependent base classes where the primary class template is known.
706 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
707 if (ParsedType TypeInBase =
708 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
709 return TypeInBase;
710 }
711
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000712 // Perform lookup for Objective-C instance variables (including automatically
713 // synthesized instance variables), if we're in an Objective-C method.
714 // FIXME: This lookup really, really needs to be folded in to the normal
715 // unqualified lookup mechanism.
716 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
717 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000718 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000719 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000720 }
721
722 bool SecondTry = false;
723 bool IsFilteredTemplateName = false;
724
725Corrected:
726 switch (Result.getResultKind()) {
727 case LookupResult::NotFound:
728 // If an unqualified-id is followed by a '(', then we have a function
729 // call.
730 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
731 // In C++, this is an ADL-only call.
732 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000733 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000734 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
735
736 // C90 6.3.2.2:
737 // If the expression that precedes the parenthesized argument list in a
738 // function call consists solely of an identifier, and if no
739 // declaration is visible for this identifier, the identifier is
740 // implicitly declared exactly as if, in the innermost block containing
741 // the function call, the declaration
742 //
743 // extern int identifier ();
744 //
745 // appeared.
746 //
747 // We also allow this in C99 as an extension.
748 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
749 Result.addDecl(D);
750 Result.resolveKind();
751 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
752 }
753 }
754
755 // In C, we first see whether there is a tag type by the same name, in
756 // which case it's likely that the user just forget to write "enum",
757 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000758 if (!getLangOpts().CPlusPlus && !SecondTry &&
759 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
760 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000761 }
762
763 // Perform typo correction to determine if there is another name that is
764 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000765 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000766 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000767 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000768 Result.getLookupKind(), S,
John Thompson2255f2c2014-04-23 12:57:01 +0000769 &SS, *CCC,
770 CTK_ErrorRecovery)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000771 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
772 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000773
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000774 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000775 NamedDecl *UnderlyingFirstDecl
Craig Topperc3ec1492014-05-26 06:22:03 +0000776 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000777 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000778 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000779 UnqualifiedDiag = diag::err_no_template_suggest;
780 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000781 } else if (UnderlyingFirstDecl &&
782 (isa<TypeDecl>(UnderlyingFirstDecl) ||
783 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
784 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000785 UnqualifiedDiag = diag::err_unknown_typename_suggest;
786 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
787 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000788
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000789 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000790 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000791 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000792 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
793 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000794 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000795 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
796 << Name << computeDeclContext(SS, false)
797 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000798 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000799
800 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000801 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000802
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000803 // Typo correction corrected to a keyword.
804 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000805 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000806
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000807 // Also update the LookupResult...
808 // FIXME: This should probably go away at some point
809 Result.clear();
810 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000811 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000812 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000813
814 // If we found an Objective-C instance variable, let
815 // LookupInObjCMethod build the appropriate expression to
816 // reference the ivar.
817 // FIXME: This is a gross hack.
818 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
819 Result.clear();
820 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000821 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000822 }
823
824 goto Corrected;
825 }
826 }
827
828 // We failed to correct; just fall through and let the parser deal with it.
829 Result.suppressDiagnostics();
830 return NameClassification::Unknown();
831
Abramo Bagnara7945c982012-01-27 09:46:47 +0000832 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000833 // We performed name lookup into the current instantiation, and there were
834 // dependent bases, so we treat this result the same way as any other
835 // dependent nested-name-specifier.
836
837 // C++ [temp.res]p2:
838 // A name used in a template declaration or definition and that is
839 // dependent on a template-parameter is assumed not to name a type
840 // unless the applicable name lookup finds a type name or the name is
841 // qualified by the keyword typename.
842 //
843 // FIXME: If the next token is '<', we might want to ask the parser to
844 // perform some heroics to see if we actually have a
845 // template-argument-list, which would indicate a missing 'template'
846 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000847 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
848 NameInfo, IsAddressOfOperand,
Craig Topperc3ec1492014-05-26 06:22:03 +0000849 /*TemplateArgs=*/nullptr);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000850 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000851
852 case LookupResult::Found:
853 case LookupResult::FoundOverloaded:
854 case LookupResult::FoundUnresolvedValue:
855 break;
856
857 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000858 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000859 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000860 // C++ [temp.local]p3:
861 // A lookup that finds an injected-class-name (10.2) can result in an
862 // ambiguity in certain cases (for example, if it is found in more than
863 // one base class). If all of the injected-class-names that are found
864 // refer to specializations of the same class template, and if the name
865 // is followed by a template-argument-list, the reference refers to the
866 // class template itself and not a specialization thereof, and is not
867 // ambiguous.
868 //
869 // This filtering can make an ambiguous result into an unambiguous one,
870 // so try again after filtering out template names.
871 FilterAcceptableTemplateNames(Result);
872 if (!Result.isAmbiguous()) {
873 IsFilteredTemplateName = true;
874 break;
875 }
876 }
877
878 // Diagnose the ambiguity and return an error.
879 return NameClassification::Error();
880 }
881
David Blaikiebbafb8a2012-03-11 07:00:24 +0000882 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000883 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
884 // C++ [temp.names]p3:
885 // After name lookup (3.4) finds that a name is a template-name or that
886 // an operator-function-id or a literal- operator-id refers to a set of
887 // overloaded functions any member of which is a function template if
888 // this is followed by a <, the < is always taken as the delimiter of a
889 // template-argument-list and never as the less-than operator.
890 if (!IsFilteredTemplateName)
891 FilterAcceptableTemplateNames(Result);
892
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000893 if (!Result.empty()) {
894 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000895 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000896 TemplateName Template;
897 if (Result.end() - Result.begin() > 1) {
898 IsFunctionTemplate = true;
899 Template = Context.getOverloadedTemplateName(Result.begin(),
900 Result.end());
901 } else {
902 TemplateDecl *TD
903 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
904 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000905 IsVarTemplate = isa<VarTemplateDecl>(TD);
906
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000907 if (SS.isSet() && !SS.isInvalid())
908 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000909 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000910 TD);
911 else
912 Template = TemplateName(TD);
913 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000914
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000915 if (IsFunctionTemplate) {
916 // Function templates always go through overload resolution, at which
917 // point we'll perform the various checks (e.g., accessibility) we need
918 // to based on which function we selected.
919 Result.suppressDiagnostics();
920
921 return NameClassification::FunctionTemplate(Template);
922 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000923
924 return IsVarTemplate ? NameClassification::VarTemplate(Template)
925 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000926 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000927 }
Richard Smith4f605af2012-08-18 00:55:03 +0000928
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000929 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000930 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
931 DiagnoseUseOfDecl(Type, NameLoc);
Nico Weber72889432014-09-06 01:25:55 +0000932 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000933 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000934 if (SS.isNotEmpty())
935 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000936 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000937 }
Richard Smith4f605af2012-08-18 00:55:03 +0000938
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000939 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
940 if (!Class) {
941 // FIXME: It's unfortunate that we don't have a Type node for handling this.
Nico Weberdfc59202014-05-03 22:07:35 +0000942 if (ObjCCompatibleAliasDecl *Alias =
943 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000944 Class = Alias->getClassInterface();
945 }
946
947 if (Class) {
948 DiagnoseUseOfDecl(Class, NameLoc);
949
950 if (NextToken.is(tok::period)) {
951 // Interface. <something> is parsed as a property reference expression.
952 // Just return "unknown" as a fall-through for now.
953 Result.suppressDiagnostics();
954 return NameClassification::Unknown();
955 }
956
957 QualType T = Context.getObjCInterfaceType(Class);
958 return ParsedType::make(T);
959 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000960
Richard Smith4f605af2012-08-18 00:55:03 +0000961 // We can have a type template here if we're classifying a template argument.
962 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
963 return NameClassification::TypeTemplate(
964 TemplateName(cast<TemplateDecl>(FirstDecl)));
965
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000966 // Check for a tag type hidden by a non-type decl in a few cases where it
967 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000968 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
969 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000970 (NextIsOp &&
971 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000972 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
973 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
974 DiagnoseUseOfDecl(Type, NameLoc);
975 QualType T = Context.getTypeDeclType(Type);
976 if (SS.isNotEmpty())
977 return buildNestedType(*this, SS, T, NameLoc);
978 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000979 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000980
Richard Smith4f605af2012-08-18 00:55:03 +0000981 if (FirstDecl->isCXXClassMember())
Craig Topperc3ec1492014-05-26 06:22:03 +0000982 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
983 nullptr);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000984
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000985 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
986 return BuildDeclarationNameExpr(SS, Result, ADL);
987}
988
John McCall5ed6e8f2009-08-18 00:00:49 +0000989// Determines the context to return to after temporarily entering a
990// context. This depends in an unnecessarily complicated way on the
991// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000992DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000993
John McCall5ed6e8f2009-08-18 00:00:49 +0000994 // Functions defined inline within classes aren't parsed until we've
995 // finished parsing the top-level class, so the top-level class is
996 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000997 // A Lambda call operator whose parent is a class must not be treated
998 // as an inline member function. A Lambda can be used legally
999 // either as an in-class member initializer or a default argument. These
1000 // are parsed once the class has been marked complete and so the containing
1001 // context would be the nested class (when the lambda is defined in one);
1002 // If the class is not complete, then the lambda is being used in an
1003 // ill-formed fashion (such as to specify the width of a bit-field, or
1004 // in an array-bound) - in which case we still want to return the
1005 // lexically containing DC (which could be a nested class).
1006 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +00001007 DC = DC->getLexicalParent();
1008
1009 // A function not defined within a class will always return to its
1010 // lexical context.
1011 if (!isa<CXXRecordDecl>(DC))
1012 return DC;
1013
1014 // A C++ inline method/friend is parsed *after* the topmost class
1015 // it was declared in is fully parsed ("complete"); the topmost
1016 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +00001017 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001018 DC = RD;
1019
1020 // Return the declaration context of the topmost class the inline method is
1021 // declared in.
1022 return DC;
1023 }
1024
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +00001025 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001026}
1027
Douglas Gregor91f84212008-12-11 16:49:14 +00001028void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001029 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +00001030 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +00001031 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +00001032 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +00001033}
1034
Chris Lattner0a5ff0d2008-04-06 04:47:34 +00001035void Sema::PopDeclContext() {
1036 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +00001037
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001038 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +00001039 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +00001040}
1041
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +00001042/// EnterDeclaratorContext - Used when we must lookup names in the context
1043/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +00001044///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001045void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +00001046 // C++0x [basic.lookup.unqual]p13:
1047 // A name used in the definition of a static data member of class
1048 // X (after the qualified-id of the static member) is looked up as
1049 // if the name was used in a member function of X.
1050 // C++0x [basic.lookup.unqual]p14:
1051 // If a variable member of a namespace is defined outside of the
1052 // scope of its namespace then any name used in the definition of
1053 // the variable member (after the declarator-id) is looked up as
1054 // if the definition of the variable member occurred in its
1055 // namespace.
1056 // Both of these imply that we should push a scope whose context
1057 // is the semantic context of the declaration. We can't use
1058 // PushDeclContext here because that context is not necessarily
1059 // lexically contained in the current context. Fortunately,
1060 // the containing scope should have the appropriate information.
1061
1062 assert(!S->getEntity() && "scope already has entity");
1063
1064#ifndef NDEBUG
1065 Scope *Ancestor = S->getParent();
1066 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1067 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1068#endif
1069
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001070 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +00001071 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001072}
1073
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001074void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +00001075 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001076
John McCall6df5fef2009-12-19 10:49:29 +00001077 // Switch back to the lexical context. The safety of this is
1078 // enforced by an assert in EnterDeclaratorContext.
1079 Scope *Ancestor = S->getParent();
1080 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +00001081 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +00001082
1083 // We don't need to do anything with the scope, which is going to
1084 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001085}
1086
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001087
1088void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +00001089 // We assume that the caller has already called
1090 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1091 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001092 if (!FD)
1093 return;
1094
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001095 // Same implementation as PushDeclContext, but enters the context
1096 // from the lexical parent, rather than the top-level class.
1097 assert(CurContext == FD->getLexicalParent() &&
1098 "The next DeclContext should be lexically contained in the current one.");
1099 CurContext = FD;
1100 S->setEntity(CurContext);
1101
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001102 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1103 ParmVarDecl *Param = FD->getParamDecl(P);
1104 // If the parameter has an identifier, then add it to the scope
1105 if (Param->getIdentifier()) {
1106 S->AddDecl(Param);
1107 IdResolver.AddDecl(Param);
1108 }
1109 }
1110}
1111
1112
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001113void Sema::ActOnExitFunctionContext() {
1114 // Same implementation as PopDeclContext, but returns to the lexical parent,
1115 // rather than the top-level class.
1116 assert(CurContext && "DeclContext imbalance!");
1117 CurContext = CurContext->getLexicalParent();
1118 assert(CurContext && "Popped translation unit!");
1119}
1120
1121
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001122/// \brief Determine whether we allow overloading of the function
1123/// PrevDecl with another declaration.
1124///
1125/// This routine determines whether overloading is possible, not
1126/// whether some new function is actually an overload. It will return
1127/// true in C++ (where we can always provide overloads) or, as an
1128/// extension, in C when the previous function is already an
1129/// overloaded function declaration or has the "overloadable"
1130/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001131static bool AllowOverloadingOfFunction(LookupResult &Previous,
1132 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001133 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001134 return true;
1135
John McCall1f82f242009-11-18 22:49:29 +00001136 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001137 return true;
1138
John McCall1f82f242009-11-18 22:49:29 +00001139 return (Previous.getResultKind() == LookupResult::Found
1140 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001141}
1142
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001143/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001144void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001145 // Move up the scope chain until we find the nearest enclosing
1146 // non-transparent context. The declaration will be introduced into this
1147 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001148 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001149 S = S->getParent();
1150
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001151 // Add scoped declarations into their context, so that they can be
1152 // found later. Declarations without a context won't be inserted
1153 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001154 if (AddToContext)
1155 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001156
Richard Smith541b38b2013-09-20 01:15:31 +00001157 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1158 // are function-local declarations.
1159 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001160 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001161 D->getLexicalDeclContext()->getRedeclContext()) &&
1162 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001163 return;
1164
1165 // Template instantiations should also not be pushed into scope.
1166 if (isa<FunctionDecl>(D) &&
1167 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001168 return;
1169
John McCall9f3059a2009-10-09 21:13:30 +00001170 // If this replaces anything in the current scope,
1171 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1172 IEnd = IdResolver.end();
1173 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001174 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1175 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001176 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001177
John McCall9f3059a2009-10-09 21:13:30 +00001178 // Should only need to replace one decl.
1179 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001180 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001181 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182
John McCall48871652010-08-21 09:40:31 +00001183 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001184
1185 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1186 // Implicitly-generated labels may end up getting generated in an order that
1187 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1188 // the label at the appropriate place in the identifier chain.
1189 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001190 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001191 if (IDC == CurContext) {
1192 if (!S->isDeclScope(*I))
1193 continue;
1194 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001195 break;
1196 }
1197
Douglas Gregor46c04e72011-03-16 16:39:03 +00001198 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001199 } else {
1200 IdResolver.AddDecl(D);
1201 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001202}
1203
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001204void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1205 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1206 TUScope->AddDecl(D);
1207}
1208
Richard Smith1c34fb72013-08-13 18:18:50 +00001209bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001210 bool AllowInlineNamespace) {
1211 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001212}
1213
John McCallcc14d1f2010-08-24 08:50:51 +00001214Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1215 DeclContext *TargetDC = DC->getPrimaryContext();
1216 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001217 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001218 if (ScopeDC->getPrimaryContext() == TargetDC)
1219 return S;
1220 } while ((S = S->getParent()));
1221
Craig Topperc3ec1492014-05-26 06:22:03 +00001222 return nullptr;
John McCallcc14d1f2010-08-24 08:50:51 +00001223}
1224
John McCall1f82f242009-11-18 22:49:29 +00001225static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1226 DeclContext*,
1227 ASTContext&);
1228
1229/// Filters out lookup results that don't fall within the given scope
1230/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001231void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001232 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001233 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001234 LookupResult::Filter F = R.makeFilter();
1235 while (F.hasNext()) {
1236 NamedDecl *D = F.next();
1237
Richard Smith72bcaec2013-12-05 04:30:04 +00001238 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001239 continue;
1240
Richard Smith72bcaec2013-12-05 04:30:04 +00001241 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001242 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001243
John McCall1f82f242009-11-18 22:49:29 +00001244 F.erase();
1245 }
1246
1247 F.done();
1248}
1249
1250static bool isUsingDecl(NamedDecl *D) {
1251 return isa<UsingShadowDecl>(D) ||
1252 isa<UnresolvedUsingTypenameDecl>(D) ||
1253 isa<UnresolvedUsingValueDecl>(D);
1254}
1255
1256/// Removes using shadow declarations from the lookup results.
1257static void RemoveUsingDecls(LookupResult &R) {
1258 LookupResult::Filter F = R.makeFilter();
1259 while (F.hasNext())
1260 if (isUsingDecl(F.next()))
1261 F.erase();
1262
1263 F.done();
1264}
1265
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001266/// \brief Check for this common pattern:
1267/// @code
1268/// class S {
1269/// S(const S&); // DO NOT IMPLEMENT
1270/// void operator=(const S&); // DO NOT IMPLEMENT
1271/// };
1272/// @endcode
1273static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1274 // FIXME: Should check for private access too but access is set after we get
1275 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001276 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001277 return false;
1278
1279 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1280 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001281 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1282 return Method->isCopyAssignmentOperator();
1283 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001284}
1285
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001286// We need this to handle
1287//
1288// typedef struct {
1289// void *foo() { return 0; }
1290// } A;
1291//
1292// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1293// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001294// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001295// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001296// Callers should verify at the end of the TU if it D has external linkage or
1297// not.
1298bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1299 const DeclContext *DC = D->getDeclContext();
1300 while (!DC->isTranslationUnit()) {
1301 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1302 if (!RD->hasNameForLinkage())
1303 return true;
1304 }
1305 DC = DC->getParent();
1306 }
1307
Rafael Espindola3ae00052013-05-13 00:12:11 +00001308 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001309}
1310
Eli Friedman5ef21752013-09-10 03:05:56 +00001311// FIXME: This needs to be refactored; some other isInMainFile users want
1312// these semantics.
1313static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1314 if (S.TUKind != TU_Complete)
1315 return false;
1316 return S.SourceMgr.isInMainFile(Loc);
1317}
1318
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001319bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1320 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001321
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001322 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1323 return false;
1324
Richard Smithc3926172014-04-02 18:28:36 +00001325 // Ignore all entities declared within templates, and out-of-line definitions
1326 // of members of class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001327 if (D->getDeclContext()->isDependentContext() ||
1328 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001329 return false;
1330
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001331 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001332 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1333 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001334
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001335 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1336 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1337 return false;
1338 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001339 // 'static inline' functions are defined in headers; don't warn.
Richard Smitha90ee352014-05-11 21:25:24 +00001340 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001341 return false;
1342 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001343
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001344 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001345 Context.DeclMustBeEmitted(FD))
1346 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001347 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001348 // Constants and utility variables are defined in headers with internal
1349 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1350 // like "inline".)
1351 if (!isMainFileLoc(*this, VD->getLocation()))
1352 return false;
1353
Eli Friedman5ef21752013-09-10 03:05:56 +00001354 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001355 return false;
1356
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001357 if (VD->isStaticDataMember() &&
1358 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1359 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001360 } else {
1361 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001362 }
1363
John McCalld37d35b2010-10-27 01:41:35 +00001364 // Only warn for unused decls internal to the translation unit.
Richard Smitha90ee352014-05-11 21:25:24 +00001365 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1366 // for inline functions defined in the main source file, for instance.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001367 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001368}
1369
1370void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001371 if (!D)
1372 return;
1373
1374 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001375 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001376 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1377 return; // First should already be in the vector.
1378 }
1379
1380 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001381 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001382 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1383 return; // First should already be in the vector.
1384 }
1385
David Blaikie3d8edc22012-05-26 05:35:39 +00001386 if (ShouldWarnIfUnusedFileScopedDecl(D))
1387 UnusedFileScopedDecls.push_back(D);
1388}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001389
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001390static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001391 if (D->isInvalidDecl())
1392 return false;
1393
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001394 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1395 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001396 return false;
John McCall67da35c2010-02-04 22:26:26 +00001397
Chris Lattnercab02a62011-02-17 20:34:02 +00001398 if (isa<LabelDecl>(D))
1399 return true;
Nico Weber72889432014-09-06 01:25:55 +00001400
1401 // Except for labels, we only care about unused decls that are local to
1402 // functions.
1403 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1404 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1405 // For dependent types, the diagnostic is deferred.
1406 WithinFunction =
1407 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1408 if (!WithinFunction)
1409 return false;
1410
1411 if (isa<TypedefNameDecl>(D))
1412 return true;
Chris Lattnercab02a62011-02-17 20:34:02 +00001413
John McCall67da35c2010-02-04 22:26:26 +00001414 // White-list anything that isn't a local variable.
Nico Weber72889432014-09-06 01:25:55 +00001415 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
John McCall67da35c2010-02-04 22:26:26 +00001416 return false;
1417
1418 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001419 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001420
1421 // White-list anything with an __attribute__((unused)) type.
1422 QualType Ty = VD->getType();
1423
1424 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001425 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001426 if (TT->getDecl()->hasAttr<UnusedAttr>())
1427 return false;
1428 }
1429
Douglas Gregor14f232e2010-05-08 23:05:03 +00001430 // If we failed to complete the type for some reason, or if the type is
1431 // dependent, don't diagnose the variable.
1432 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001433 return false;
1434
John McCallcef15822010-03-31 02:47:45 +00001435 if (const TagType *TT = Ty->getAs<TagType>()) {
1436 const TagDecl *Tag = TT->getDecl();
1437 if (Tag->hasAttr<UnusedAttr>())
1438 return false;
1439
1440 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001441 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001442 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001443
1444 if (const Expr *Init = VD->getInit()) {
Nico Weberdfc59202014-05-03 22:07:35 +00001445 if (const ExprWithCleanups *Cleanups =
1446 dyn_cast<ExprWithCleanups>(Init))
David Blaikiea9d4a932012-10-24 21:29:06 +00001447 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001448 const CXXConstructExpr *Construct =
1449 dyn_cast<CXXConstructExpr>(Init);
1450 if (Construct && !Construct->isElidable()) {
1451 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001452 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001453 return false;
1454 }
1455 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001456 }
1457 }
John McCallcef15822010-03-31 02:47:45 +00001458
1459 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001460 }
1461
John McCall67da35c2010-02-04 22:26:26 +00001462 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001463}
1464
Anna Zaks964f4c62011-07-28 20:52:06 +00001465static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1466 FixItHint &Hint) {
1467 if (isa<LabelDecl>(D)) {
1468 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001469 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001470 if (AfterColon.isInvalid())
1471 return;
1472 Hint = FixItHint::CreateRemoval(CharSourceRange::
1473 getCharRange(D->getLocStart(), AfterColon));
1474 }
1475 return;
1476}
1477
Nico Weber72889432014-09-06 01:25:55 +00001478void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1479 if (D->getTypeForDecl()->isDependentType())
1480 return;
1481
1482 for (auto *TmpD : D->decls()) {
1483 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1484 DiagnoseUnusedDecl(T);
1485 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1486 DiagnoseUnusedNestedTypedefs(R);
1487 }
1488}
1489
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001490/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1491/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001492void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1493 if (!ShouldDiagnoseUnusedDecl(D))
1494 return;
Nico Weber72889432014-09-06 01:25:55 +00001495
1496 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1497 // typedefs can be referenced later on, so the diagnostics are emitted
1498 // at end-of-translation-unit.
1499 UnusedLocalTypedefNameCandidates.insert(TD);
1500 return;
1501 }
Douglas Gregor14f232e2010-05-08 23:05:03 +00001502
Nico Weberdfc59202014-05-03 22:07:35 +00001503 FixItHint Hint;
Anna Zaks964f4c62011-07-28 20:52:06 +00001504 GenerateFixForUnusedDecl(D, Context, Hint);
1505
Chris Lattnercab02a62011-02-17 20:34:02 +00001506 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001507 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001508 DiagID = diag::warn_unused_exception_param;
1509 else if (isa<LabelDecl>(D))
1510 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001511 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001512 DiagID = diag::warn_unused_variable;
1513
Anna Zaks964f4c62011-07-28 20:52:06 +00001514 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001515}
1516
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001517static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1518 // Verify that we have no forward references left. If so, there was a goto
1519 // or address of a label taken, but no definition of it. Label fwd
Ehsan Akhgari31097582014-09-22 02:21:54 +00001520 // definitions are indicated with a null substmt which is also not a resolved
1521 // MS inline assembly label name.
1522 bool Diagnose = false;
1523 if (L->isMSAsmLabel())
1524 Diagnose = !L->isResolvedMSAsmLabel();
1525 else
1526 Diagnose = L->getStmt() == nullptr;
1527 if (Diagnose)
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001528 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1529}
1530
Steve Naroffc62adb62007-10-09 22:01:59 +00001531void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00001532 S->mergeNRVOIntoParent();
1533
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001534 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001535 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001536 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001537
Aaron Ballman35c54952014-03-17 16:55:25 +00001538 for (auto *TmpD : S->decls()) {
Steve Naroff9324db12007-09-13 18:10:37 +00001539 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001540
Douglas Gregor91f84212008-12-11 16:49:14 +00001541 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1542 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001543
Douglas Gregor91f84212008-12-11 16:49:14 +00001544 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001545
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001546 // Diagnose unused variables in this scope.
Nico Weber72889432014-09-06 01:25:55 +00001547 if (!S->hasUnrecoverableErrorOccurred()) {
Douglas Gregor14f232e2010-05-08 23:05:03 +00001548 DiagnoseUnusedDecl(D);
Nico Weber72889432014-09-06 01:25:55 +00001549 if (const auto *RD = dyn_cast<RecordDecl>(D))
1550 DiagnoseUnusedNestedTypedefs(RD);
1551 }
Douglas Gregor14f232e2010-05-08 23:05:03 +00001552
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001553 // If this was a forward reference to a label, verify it was defined.
1554 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1555 CheckPoppedLabel(LD, *this);
1556
Douglas Gregor91f84212008-12-11 16:49:14 +00001557 // Remove this name from our lexical scope.
1558 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001559 }
1560}
1561
Douglas Gregor1c283312010-08-11 12:19:30 +00001562/// \brief Look for an Objective-C class in the translation unit.
1563///
1564/// \param Id The name of the Objective-C class we're looking for. If
1565/// typo-correction fixes this name, the Id will be updated
1566/// to the fixed name.
1567///
1568/// \param IdLoc The location of the name in the translation unit.
1569///
James Dennett41725122012-06-22 10:16:05 +00001570/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001571/// if there is no class with the given name.
1572///
1573/// \returns The declaration of the named Objective-C class, or NULL if the
1574/// class could not be found.
1575ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1576 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001577 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001578 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1579 // creation from this context.
1580 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1581
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001582 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001583 // Perform typo correction at the given location, but only if we
1584 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001585 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1586 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
Craig Topperc3ec1492014-05-26 06:22:03 +00001587 LookupOrdinaryName, TUScope, nullptr,
John Thompson2255f2c2014-04-23 12:57:01 +00001588 Validator, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001589 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001590 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001591 Id = IDecl->getIdentifier();
1592 }
1593 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001594 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1595 // This routine must always return a class definition, if any.
1596 if (Def && Def->getDefinition())
1597 Def = Def->getDefinition();
1598 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001599}
1600
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001601/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1602/// from S, where a non-field would be declared. This routine copes
1603/// with the difference between C and C++ scoping rules in structs and
1604/// unions. For example, the following code is well-formed in C but
1605/// ill-formed in C++:
1606/// @code
1607/// struct S6 {
1608/// enum { BAR } e;
1609/// };
Mike Stump11289f42009-09-09 15:08:12 +00001610///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001611/// void test_S6() {
1612/// struct S6 a;
1613/// a.e = BAR;
1614/// }
1615/// @endcode
1616/// For the declaration of BAR, this routine will return a different
1617/// scope. The scope S will be the scope of the unnamed enumeration
1618/// within S6. In C++, this routine will return the scope associated
1619/// with S6, because the enumeration's scope is a transparent
1620/// context but structures can contain non-field names. In C, this
1621/// routine will return the translation unit scope, since the
1622/// enumeration's scope is a transparent context and structures cannot
1623/// contain non-field names.
1624Scope *Sema::getNonFieldDeclScope(Scope *S) {
1625 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001626 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001627 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001628 S = S->getParent();
1629 return S;
1630}
1631
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001632/// \brief Looks up the declaration of "struct objc_super" and
1633/// saves it for later use in building builtin declaration of
1634/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1635/// pre-existing declaration exists no action takes place.
1636static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1637 IdentifierInfo *II) {
1638 if (!II->isStr("objc_msgSendSuper"))
1639 return;
1640 ASTContext &Context = ThisSema.Context;
1641
1642 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1643 SourceLocation(), Sema::LookupTagName);
1644 ThisSema.LookupName(Result, S);
1645 if (Result.getResultKind() == LookupResult::Found)
1646 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1647 Context.setObjCSuperType(Context.getTagDeclType(TD));
1648}
1649
Alp Toker5d96e0a2014-07-11 20:53:51 +00001650static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1651 switch (Error) {
1652 case ASTContext::GE_None:
1653 return "";
1654 case ASTContext::GE_Missing_stdio:
1655 return "stdio.h";
1656 case ASTContext::GE_Missing_setjmp:
1657 return "setjmp.h";
1658 case ASTContext::GE_Missing_ucontext:
1659 return "ucontext.h";
1660 }
1661 llvm_unreachable("unhandled error kind");
1662}
1663
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001664/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1665/// file scope. lazily create a decl for it. ForRedeclaration is true
1666/// if we're creating this built-in in anticipation of redeclaring the
1667/// built-in.
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001668NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001669 Scope *S, bool ForRedeclaration,
1670 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001671 LookupPredefedObjCSuperType(*this, S, II);
Chris Lattner9561a0b2007-01-28 08:20:04 +00001672
Chris Lattnerecd79c62009-06-14 00:45:47 +00001673 ASTContext::GetBuiltinTypeError Error;
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001674 QualType R = Context.GetBuiltinType(ID, Error);
Alp Toker5d96e0a2014-07-11 20:53:51 +00001675 if (Error) {
Douglas Gregor538c3d82009-02-14 01:52:53 +00001676 if (ForRedeclaration)
Alp Toker5d96e0a2014-07-11 20:53:51 +00001677 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1678 << getHeaderName(Error)
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001679 << Context.BuiltinInfo.GetName(ID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001680 return nullptr;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001681 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001682
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001683 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001684 Diag(Loc, diag::ext_implicit_lib_function_decl)
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001685 << Context.BuiltinInfo.GetName(ID)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001686 << R;
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001687 if (Context.BuiltinInfo.getHeaderName(ID) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001688 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
Alp Toker5d96e0a2014-07-11 20:53:51 +00001689 Diag(Loc, diag::note_include_header_or_declare)
Alexey Samsonov75bb28e2014-08-28 23:34:32 +00001690 << Context.BuiltinInfo.getHeaderName(ID)
1691 << Context.BuiltinInfo.GetName(ID);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001692 }
1693
Warren Hunt445d83e2013-11-01 23:46:51 +00001694 DeclContext *Parent = Context.getTranslationUnitDecl();
1695 if (getLangOpts().CPlusPlus) {
1696 LinkageSpecDecl *CLinkageDecl =
1697 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1698 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001699 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001700 Parent->addDecl(CLinkageDecl);
1701 Parent = CLinkageDecl;
1702 }
1703
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001704 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001705 Parent,
Craig Topperc3ec1492014-05-26 06:22:03 +00001706 Loc, Loc, II, R, /*TInfo=*/nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001707 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001708 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001709 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001710 New->setImplicit();
1711
Chris Lattner4dd27102008-05-05 22:18:14 +00001712 // Create Decl objects for each parameter, adding them to the
1713 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001714 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001715 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001716 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001717 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001718 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001719 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1720 SC_None, nullptr);
John McCall8fb0d9d2011-05-01 22:35:37 +00001721 parm->setScopeInfo(0, i);
1722 Params.push_back(parm);
1723 }
David Blaikie9c70e042011-09-21 18:16:56 +00001724 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
1727 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001728 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001729
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001730 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001731 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1732 // relate Scopes to DeclContexts, and probably eliminate CurContext
1733 // entirely, but we're not there yet.
1734 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001735 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001736 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001737 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001738 return New;
1739}
1740
Douglas Gregor3552dab2013-01-09 00:47:56 +00001741/// \brief Filter out any previous declarations that the given declaration
1742/// should not consider because they are not permitted to conflict, e.g.,
1743/// because they come from hidden sub-modules and do not refer to the same
1744/// entity.
1745static void filterNonConflictingPreviousDecls(ASTContext &context,
1746 NamedDecl *decl,
1747 LookupResult &previous){
1748 // This is only interesting when modules are enabled.
1749 if (!context.getLangOpts().Modules)
1750 return;
1751
1752 // Empty sets are uninteresting.
1753 if (previous.empty())
1754 return;
1755
Douglas Gregor3552dab2013-01-09 00:47:56 +00001756 LookupResult::Filter filter = previous.makeFilter();
1757 while (filter.hasNext()) {
1758 NamedDecl *old = filter.next();
1759
1760 // Non-hidden declarations are never ignored.
1761 if (!old->isHidden())
1762 continue;
1763
Rafael Espindola3ae00052013-05-13 00:12:11 +00001764 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001765 filter.erase();
1766 }
1767
1768 filter.done();
1769}
1770
Richard Smithca40f9b2014-08-10 02:20:15 +00001771/// Typedef declarations don't have linkage, but they still denote the same
1772/// entity if their types are the same.
1773/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1774/// isSameEntity.
1775static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context,
1776 TypedefNameDecl *Decl,
1777 LookupResult &Previous) {
1778 // This is only interesting when modules are enabled.
1779 if (!Context.getLangOpts().Modules)
1780 return;
1781
1782 // Empty sets are uninteresting.
1783 if (Previous.empty())
1784 return;
1785
1786 LookupResult::Filter Filter = Previous.makeFilter();
1787 while (Filter.hasNext()) {
1788 NamedDecl *Old = Filter.next();
1789
1790 // Non-hidden declarations are never ignored.
1791 if (!Old->isHidden())
1792 continue;
1793
1794 // Declarations of the same entity are not ignored, even if they have
1795 // different linkages.
1796 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old))
1797 if (Context.hasSameType(OldTD->getUnderlyingType(),
1798 Decl->getUnderlyingType()))
1799 continue;
1800
1801 if (!Old->isExternallyVisible())
1802 Filter.erase();
1803 }
1804
1805 Filter.done();
1806}
1807
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001808bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1809 QualType OldType;
1810 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1811 OldType = OldTypedef->getUnderlyingType();
1812 else
1813 OldType = Context.getTypeDeclType(Old);
1814 QualType NewType = New->getUnderlyingType();
1815
Douglas Gregoraab36982012-01-11 22:33:48 +00001816 if (NewType->isVariablyModifiedType()) {
1817 // Must not redefine a typedef with a variably-modified type.
1818 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1819 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1820 << Kind << NewType;
1821 if (Old->getLocation().isValid())
1822 Diag(Old->getLocation(), diag::note_previous_definition);
1823 New->setInvalidDecl();
1824 return true;
1825 }
1826
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001827 if (OldType != NewType &&
1828 !OldType->isDependentType() &&
1829 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001830 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001831 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1832 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1833 << Kind << NewType << OldType;
1834 if (Old->getLocation().isValid())
1835 Diag(Old->getLocation(), diag::note_previous_definition);
1836 New->setInvalidDecl();
1837 return true;
1838 }
1839 return false;
1840}
1841
Richard Smithdda56e42011-04-15 14:24:37 +00001842/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001843/// same name and scope as a previous declaration 'Old'. Figure out
1844/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001845/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001846///
Richard Smithdda56e42011-04-15 14:24:37 +00001847void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001848 // If the new decl is known invalid already, don't bother doing any
1849 // merging checks.
1850 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001851
Steve Naroff44cfcb62008-09-09 14:32:20 +00001852 // Allow multiple definitions for ObjC built-in typedefs.
1853 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001854 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001855 const IdentifierInfo *TypeID = New->getIdentifier();
1856 switch (TypeID->getLength()) {
1857 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001858 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001859 {
1860 if (!TypeID->isStr("id"))
1861 break;
1862 QualType T = New->getUnderlyingType();
1863 if (!T->isPointerType())
1864 break;
1865 if (!T->isVoidPointerType()) {
1866 QualType PT = T->getAs<PointerType>()->getPointeeType();
1867 if (!PT->isStructureType())
1868 break;
1869 }
1870 Context.setObjCIdRedefinitionType(T);
1871 // Install the built-in type for 'id', ignoring the current definition.
1872 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1873 return;
1874 }
Chris Lattner66e32812008-11-20 05:41:43 +00001875 case 5:
1876 if (!TypeID->isStr("Class"))
1877 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001878 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001879 // Install the built-in type for 'Class', ignoring the current definition.
1880 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001881 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001882 case 3:
1883 if (!TypeID->isStr("SEL"))
1884 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001885 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001886 // Install the built-in type for 'SEL', ignoring the current definition.
1887 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001888 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001889 }
1890 // Fall through - the typedef name was not a builtin type.
1891 }
John McCall1f82f242009-11-18 22:49:29 +00001892
Douglas Gregorfb034662009-01-28 17:15:10 +00001893 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001894 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1895 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001896 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001897 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001898
1899 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001900 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001901 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001902
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001903 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001904 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001905
John McCall1f82f242009-11-18 22:49:29 +00001906 // If the old declaration is invalid, just give up here.
1907 if (Old->isInvalidDecl())
1908 return New->setInvalidDecl();
1909
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001910 // If the typedef types are not identical, reject them in all languages and
1911 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001912 if (isIncompatibleTypedef(Old, New))
1913 return;
Mike Stump11289f42009-09-09 15:08:12 +00001914
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001915 // The types match. Link up the redeclaration chain and merge attributes if
1916 // the old declaration was a typedef.
1917 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001918 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001919 mergeDeclAttributes(New, Old);
1920 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001921
David Blaikiebbafb8a2012-03-11 07:00:24 +00001922 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001923 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001924
David Blaikiebbafb8a2012-03-11 07:00:24 +00001925 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001926 // C++ [dcl.typedef]p2:
1927 // In a given non-class scope, a typedef specifier can be used to
1928 // redefine the name of any type declared in that scope to refer
1929 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001930 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001931 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001932
1933 // C++0x [dcl.typedef]p4:
1934 // In a given class scope, a typedef specifier can be used to redefine
1935 // any class-name declared in that scope that is not also a typedef-name
1936 // to refer to the type to which it already refers.
1937 //
1938 // This wording came in via DR424, which was a correction to the
1939 // wording in DR56, which accidentally banned code like:
1940 //
1941 // struct S {
1942 // typedef struct A { } A;
1943 // };
1944 //
1945 // in the C++03 standard. We implement the C++0x semantics, which
1946 // allow the above but disallow
1947 //
1948 // struct S {
1949 // typedef int I;
1950 // typedef int I;
1951 // };
1952 //
1953 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001954 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001955 return;
1956
Chris Lattner2581fc32009-04-17 22:04:20 +00001957 Diag(New->getLocation(), diag::err_redefinition)
1958 << New->getDeclName();
1959 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001960 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001961 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001962
Douglas Gregor7363fb02012-01-11 04:25:01 +00001963 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001964 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001965 return;
1966
Chris Lattner2581fc32009-04-17 22:04:20 +00001967 // If we have a redefinition of a typedef in C, emit a warning. This warning
1968 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001969 // -Wtypedef-redefinition. If either the original or the redefinition is
1970 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001971 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001972 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1973 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001974 return;
Mike Stump11289f42009-09-09 15:08:12 +00001975
Richard Smith1b98ccc2014-07-19 01:39:17 +00001976 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
Chris Lattner2581fc32009-04-17 22:04:20 +00001977 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001978 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001979 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001980}
1981
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001982/// DeclhasAttr - returns true if decl Declaration already has the target
1983/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001984static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001985 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001986 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001987 for (const auto *i : D->attrs())
1988 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001989 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001990 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001991 return true;
1992 continue;
1993 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001994 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001995 if (OA && isa<OwnershipAttr>(i))
1996 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001997 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001998 }
Chris Lattner84966392008-03-03 03:28:21 +00001999
2000 return false;
2001}
2002
Richard Smithbc8caaf2013-02-22 04:55:39 +00002003static bool isAttributeTargetADefinition(Decl *D) {
2004 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2005 return VD->isThisDeclarationADefinition();
2006 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2007 return TD->isCompleteDefinition() || TD->isBeingDefined();
2008 return true;
2009}
2010
2011/// Merge alignment attributes from \p Old to \p New, taking into account the
2012/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2013///
2014/// \return \c true if any attributes were added to \p New.
2015static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2016 // Look for alignas attributes on Old, and pick out whichever attribute
2017 // specifies the strictest alignment requirement.
Craig Topperc3ec1492014-05-26 06:22:03 +00002018 AlignedAttr *OldAlignasAttr = nullptr;
2019 AlignedAttr *OldStrictestAlignAttr = nullptr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002020 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002021 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002022 // FIXME: We have no way of representing inherited dependent alignments
2023 // in a case like:
2024 // template<int A, int B> struct alignas(A) X;
2025 // template<int A, int B> struct alignas(B) X {};
2026 // For now, we just ignore any alignas attributes which are not on the
2027 // definition in such a case.
2028 if (I->isAlignmentDependent())
2029 return false;
2030
2031 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002032 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002033
2034 unsigned Align = I->getAlignment(S.Context);
2035 if (Align > OldAlign) {
2036 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002037 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002038 }
2039 }
2040
2041 // Look for alignas attributes on New.
Craig Topperc3ec1492014-05-26 06:22:03 +00002042 AlignedAttr *NewAlignasAttr = nullptr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002043 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002044 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002045 if (I->isAlignmentDependent())
2046 return false;
2047
2048 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002049 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002050
2051 unsigned Align = I->getAlignment(S.Context);
2052 if (Align > NewAlign)
2053 NewAlign = Align;
2054 }
2055
2056 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2057 // Both declarations have 'alignas' attributes. We require them to match.
2058 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2059 // fall short. (If two declarations both have alignas, they must both match
2060 // every definition, and so must match each other if there is a definition.)
2061
2062 // If either declaration only contains 'alignas(0)' specifiers, then it
2063 // specifies the natural alignment for the type.
2064 if (OldAlign == 0 || NewAlign == 0) {
2065 QualType Ty;
2066 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2067 Ty = VD->getType();
2068 else
2069 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2070
2071 if (OldAlign == 0)
2072 OldAlign = S.Context.getTypeAlign(Ty);
2073 if (NewAlign == 0)
2074 NewAlign = S.Context.getTypeAlign(Ty);
2075 }
2076
2077 if (OldAlign != NewAlign) {
2078 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2079 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2080 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2081 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2082 }
2083 }
2084
2085 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2086 // C++11 [dcl.align]p6:
2087 // if any declaration of an entity has an alignment-specifier,
2088 // every defining declaration of that entity shall specify an
2089 // equivalent alignment.
2090 // C11 6.7.5/7:
2091 // If the definition of an object does not have an alignment
2092 // specifier, any other declaration of that object shall also
2093 // have no alignment specifier.
2094 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002095 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002096 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002097 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002098 }
2099
2100 bool AnyAdded = false;
2101
2102 // Ensure we have an attribute representing the strictest alignment.
2103 if (OldAlign > NewAlign) {
2104 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2105 Clone->setInherited(true);
2106 New->addAttr(Clone);
2107 AnyAdded = true;
2108 }
2109
2110 // Ensure we have an alignas attribute if the old declaration had one.
2111 if (OldAlignasAttr && !NewAlignasAttr &&
2112 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2113 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2114 Clone->setInherited(true);
2115 New->addAttr(Clone);
2116 AnyAdded = true;
2117 }
2118
2119 return AnyAdded;
2120}
2121
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002122static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2123 const InheritableAttr *Attr, bool Override) {
2124 InheritableAttr *NewAttr = nullptr;
Michael Han99315932013-01-24 16:46:58 +00002125 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002126 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002127 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2128 AA->getIntroduced(), AA->getDeprecated(),
2129 AA->getObsoleted(), AA->getUnavailable(),
2130 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00002131 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002132 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002133 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2134 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002135 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002136 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2137 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002138 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002139 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2140 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002141 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002142 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2143 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002144 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002145 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2146 FA->getFormatIdx(), FA->getFirstArg(),
2147 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002148 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002149 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2150 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002151 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00002152 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2153 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00002154 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00002155 else if (isa<AlignedAttr>(Attr))
2156 // AlignedAttrs are handled separately, because we need to handle all
2157 // such attributes on a declaration at the same time.
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002158 NewAttr = nullptr;
Fariborz Jahanianb93355e2014-07-17 17:05:04 +00002159 else if (isa<DeprecatedAttr>(Attr) && Override)
2160 NewAttr = nullptr;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00002161 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002162 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00002163
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002164 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002165 NewAttr->setInherited(true);
2166 D->addAttr(NewAttr);
2167 return true;
2168 }
2169
2170 return false;
2171}
2172
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002173static const Decl *getDefinition(const Decl *D) {
2174 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00002175 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002176 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2177 const VarDecl *Def = VD->getDefinition();
2178 if (Def)
2179 return Def;
2180 return VD->getActingDefinition();
2181 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002182 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00002183 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002184 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00002185 return Def;
2186 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002187 return nullptr;
Rafael Espindola36191042012-05-18 01:47:00 +00002188}
2189
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002190static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002191 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002192 if (Attribute->getKind() == Kind)
2193 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002194 return false;
2195}
2196
2197/// checkNewAttributesAfterDef - If we already have a definition, check that
2198/// there are no new attributes in this declaration.
2199static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2200 if (!New->hasAttrs())
2201 return;
2202
2203 const Decl *Def = getDefinition(Old);
2204 if (!Def || Def == New)
2205 return;
2206
2207 AttrVec &NewAttributes = New->getAttrs();
2208 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2209 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002210
2211 if (isa<AliasAttr>(NewAttribute)) {
2212 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2213 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2214 else {
2215 VarDecl *VD = cast<VarDecl>(New);
2216 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2217 VarDecl::TentativeDefinition
2218 ? diag::err_alias_after_tentative
2219 : diag::err_redefinition;
2220 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2221 S.Diag(Def->getLocation(), diag::note_previous_definition);
2222 VD->setInvalidDecl();
2223 }
2224 ++I;
2225 continue;
2226 }
2227
2228 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2229 // Tentative definitions are only interesting for the alias check above.
2230 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2231 ++I;
2232 continue;
2233 }
2234 }
2235
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002236 if (hasAttribute(Def, NewAttribute->getKind())) {
2237 ++I;
2238 continue; // regular attr merging will take care of validating this.
2239 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002240
Richard Smithdebc59d2013-01-30 05:45:05 +00002241 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002242 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002243 ++I;
2244 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002245 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2246 if (AA->isAlignas()) {
2247 // C++11 [dcl.align]p6:
2248 // if any declaration of an entity has an alignment-specifier,
2249 // every defining declaration of that entity shall specify an
2250 // equivalent alignment.
2251 // C11 6.7.5/7:
2252 // If the definition of an object does not have an alignment
2253 // specifier, any other declaration of that object shall also
2254 // have no alignment specifier.
2255 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002256 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002257 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002258 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002259 NewAttributes.erase(NewAttributes.begin() + I);
2260 --E;
2261 continue;
2262 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002263 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002264
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002265 S.Diag(NewAttribute->getLocation(),
2266 diag::warn_attribute_precede_definition);
2267 S.Diag(Def->getLocation(), diag::note_previous_definition);
2268 NewAttributes.erase(NewAttributes.begin() + I);
2269 --E;
2270 }
2271}
2272
John McCallf79e87d2011-03-02 04:00:57 +00002273/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002274void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002275 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002276 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2277 UsedAttr *NewAttr = OldAttr->clone(Context);
2278 NewAttr->setInherited(true);
2279 New->addAttr(NewAttr);
2280 }
2281
Richard Smithe233fbf2013-01-28 22:42:45 +00002282 if (!Old->hasAttrs() && !New->hasAttrs())
2283 return;
2284
Rafael Espindola36191042012-05-18 01:47:00 +00002285 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002286 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002287
Douglas Gregor32c17572012-01-01 20:30:41 +00002288 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002289 return;
John McCallf79e87d2011-03-02 04:00:57 +00002290
Douglas Gregor32c17572012-01-01 20:30:41 +00002291 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002292
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002293 // Ensure that any moving of objects within the allocated map is done before
2294 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002295 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002296
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002297 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002298 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002299 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002300 if (isa<DeprecatedAttr>(I) ||
2301 isa<UnavailableAttr>(I) ||
2302 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002303 switch (AMK) {
2304 case AMK_None:
2305 continue;
John McCalld2930c22011-07-22 02:45:48 +00002306
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002307 case AMK_Redeclaration:
2308 break;
2309
2310 case AMK_Override:
2311 Override = true;
2312 break;
2313 }
2314 }
2315
Rafael Espindolab0938852013-10-25 01:28:12 +00002316 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002317 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002318 continue;
2319
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002320 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002321 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002322 }
John McCallf79e87d2011-03-02 04:00:57 +00002323
Richard Smithbc8caaf2013-02-22 04:55:39 +00002324 if (mergeAlignedAttrs(*this, New, Old))
2325 foundAny = true;
2326
Douglas Gregor32c17572012-01-01 20:30:41 +00002327 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002328}
2329
2330/// mergeParamDeclAttributes - Copy attributes from the old parameter
2331/// to the new one.
2332static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2333 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002334 Sema &S) {
2335 // C++11 [dcl.attr.depend]p2:
2336 // The first declaration of a function shall specify the
2337 // carries_dependency attribute for its declarator-id if any declaration
2338 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002339 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2340 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2341 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002342 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2343 // Find the first declaration of the parameter.
2344 // FIXME: Should we build redeclaration chains for function parameters?
2345 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002346 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002347 const ParmVarDecl *FirstVD =
2348 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2349 S.Diag(FirstVD->getLocation(),
2350 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2351 }
2352
John McCallf79e87d2011-03-02 04:00:57 +00002353 if (!oldDecl->hasAttrs())
2354 return;
2355
2356 bool foundAny = newDecl->hasAttrs();
2357
2358 // Ensure that any moving of objects within the allocated map is
2359 // done before we process them.
2360 if (!foundAny) newDecl->setAttrs(AttrVec());
2361
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002362 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2363 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002364 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002365 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002366 newAttr->setInherited(true);
2367 newDecl->addAttr(newAttr);
2368 foundAny = true;
2369 }
2370 }
2371
2372 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002373}
2374
Dan Gohman28ade552010-07-26 21:25:24 +00002375namespace {
2376
Douglas Gregora74a2972009-03-06 22:43:54 +00002377/// Used in MergeFunctionDecl to keep track of function parameters in
2378/// C.
2379struct GNUCompatibleParamWarning {
2380 ParmVarDecl *OldParm;
2381 ParmVarDecl *NewParm;
2382 QualType PromotedType;
2383};
2384
Dan Gohman28ade552010-07-26 21:25:24 +00002385}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002386
2387/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002388Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002389 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002390 if (Ctor->isDefaultConstructor())
2391 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002392
2393 if (Ctor->isCopyConstructor())
2394 return Sema::CXXCopyConstructor;
2395
2396 if (Ctor->isMoveConstructor())
2397 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002398 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002399 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002400 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002401 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002402 } else if (MD->isMoveAssignmentOperator()) {
2403 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002404 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002405
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002406 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002407}
2408
David Majnemer5b63fa02014-06-18 23:26:25 +00002409// Determine whether the previous declaration was a definition, implicit
2410// declaration, or a declaration.
2411template <typename T>
2412static std::pair<diag::kind, SourceLocation>
2413getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2414 diag::kind PrevDiag;
2415 SourceLocation OldLocation = Old->getLocation();
2416 if (Old->isThisDeclarationADefinition())
2417 PrevDiag = diag::note_previous_definition;
2418 else if (Old->isImplicit()) {
2419 PrevDiag = diag::note_previous_implicit_declaration;
2420 if (OldLocation.isInvalid())
2421 OldLocation = New->getLocation();
2422 } else
2423 PrevDiag = diag::note_previous_declaration;
2424 return std::make_pair(PrevDiag, OldLocation);
2425}
2426
Sebastian Redl243d9052010-06-09 21:17:41 +00002427/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002428/// only extern inline functions can be redefined, and even then only in
2429/// GNU89 mode.
2430static bool canRedefineFunction(const FunctionDecl *FD,
2431 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002432 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2433 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002434 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002435 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002436}
2437
Reid Kleckner78af0702013-08-27 23:08:25 +00002438const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2439 const AttributedType *AT = T->getAs<AttributedType>();
2440 while (AT && !AT->isCallingConv())
2441 AT = AT->getModifiedType()->getAs<AttributedType>();
2442 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002443}
2444
Benjamin Kramer3e350262013-02-15 12:30:38 +00002445template <typename T>
2446static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002447 const DeclContext *DC = Old->getDeclContext();
2448 if (DC->isRecord())
2449 return false;
2450
2451 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002452 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002453 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002454 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002455 return true;
2456 return false;
2457}
2458
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002459/// MergeFunctionDecl - We just parsed a function 'New' from
2460/// declarator D which has the same name and scope as a previous
2461/// declaration 'Old'. Figure out how to resolve this situation,
2462/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002463///
2464/// In C++, New and Old must be declarations that are not
2465/// overloaded. Use IsOverload to determine whether New and Old are
2466/// overloaded, and to select the Old declaration that New should be
2467/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002468///
2469/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002470bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2471 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002472 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002473 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002474 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002475 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002476 if (New->getFriendObjectKind()) {
2477 Diag(New->getLocation(), diag::err_using_decl_friend);
2478 Diag(Shadow->getTargetDecl()->getLocation(),
2479 diag::note_using_decl_target);
2480 Diag(Shadow->getUsingDecl()->getLocation(),
2481 diag::note_using_decl) << 0;
2482 return true;
2483 }
2484
Richard Smith18819302014-02-06 01:31:33 +00002485 // C++11 [namespace.udecl]p14:
2486 // If a function declaration in namespace scope or block scope has the
2487 // same name and the same parameter-type-list as a function introduced
2488 // by a using-declaration, and the declarations do not declare the same
2489 // function, the program is ill-formed.
2490
2491 // Check whether the two declarations might declare the same function.
2492 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2493 if (Old &&
2494 !Old->getDeclContext()->getRedeclContext()->Equals(
2495 New->getDeclContext()->getRedeclContext()) &&
2496 !(Old->isExternC() && New->isExternC()))
Craig Topperc3ec1492014-05-26 06:22:03 +00002497 Old = nullptr;
Richard Smith18819302014-02-06 01:31:33 +00002498
2499 if (!Old) {
2500 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2501 Diag(Shadow->getTargetDecl()->getLocation(),
2502 diag::note_using_decl_target);
2503 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2504 return true;
2505 }
2506 OldD = Old;
2507 } else {
2508 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2509 << New->getDeclName();
2510 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002511 return true;
2512 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002513 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002514
David Majnemerea5092a2013-07-07 23:49:50 +00002515 // If the old declaration is invalid, just give up here.
2516 if (Old->isInvalidDecl())
2517 return true;
2518
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002519 diag::kind PrevDiag;
David Majnemer5b63fa02014-06-18 23:26:25 +00002520 SourceLocation OldLocation;
2521 std::tie(PrevDiag, OldLocation) =
2522 getNoteDiagForInvalidRedeclaration(Old, New);
Mike Stump11289f42009-09-09 15:08:12 +00002523
Charles Davisfea48452010-02-18 02:00:42 +00002524 // Don't complain about this if we're in GNU89 mode and the old function
2525 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002526 // Don't complain about specializations. They are not supposed to have
2527 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002528 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002529 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002530 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002531 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002532 !canRedefineFunction(Old, getLangOpts())) {
2533 if (getLangOpts().MicrosoftExt) {
David Majnemer5b63fa02014-06-18 23:26:25 +00002534 Diag(New->getLocation(), diag::ext_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002535 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002536 } else {
2537 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002538 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002539 return true;
2540 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002541 }
2542
Reid Kleckner78af0702013-08-27 23:08:25 +00002543
2544 // If a function is first declared with a calling convention, but is later
2545 // declared or defined without one, all following decls assume the calling
2546 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002547 //
John McCalla5f46fb2012-08-25 02:00:03 +00002548 // It's OK if a function is first declared without a calling convention,
2549 // but is later declared or defined with the default calling convention.
2550 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002551 // To test if either decl has an explicit calling convention, we look for
2552 // AttributedType sugar nodes on the type as written. If they are missing or
2553 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002554 //
2555 // Note also that we DO NOT return at this point, because we still have
2556 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002557 QualType OldQType = Context.getCanonicalType(Old->getType());
2558 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002559 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002560 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002561 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2562 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2563 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002564
Reid Kleckner78af0702013-08-27 23:08:25 +00002565 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002566 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002567 const FunctionType *FT =
2568 First->getType().getCanonicalType()->castAs<FunctionType>();
2569 FunctionType::ExtInfo FI = FT->getExtInfo();
2570 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2571 if (!NewCCExplicit) {
2572 // Inherit the CC from the previous declaration if it was specified
2573 // there but not here.
2574 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2575 RequiresAdjustment = true;
2576 } else {
2577 // Calling conventions aren't compatible, so complain.
2578 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2579 Diag(New->getLocation(), diag::err_cconv_change)
2580 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2581 << !FirstCCExplicit
2582 << (!FirstCCExplicit ? "" :
2583 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002584
Reid Kleckner78af0702013-08-27 23:08:25 +00002585 // Put the note on the first decl, since it is the one that matters.
2586 Diag(First->getLocation(), diag::note_previous_declaration);
2587 return true;
2588 }
John McCallcddbad02010-02-04 05:44:44 +00002589 }
2590
John McCallab26cfa2010-02-05 21:31:56 +00002591 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002592 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2593 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2594 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002595 }
2596
Douglas Gregor77e274f2010-06-18 21:30:25 +00002597 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002598 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2599 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2600 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002601 Diag(New->getLocation(), diag::err_regparm_mismatch)
2602 << NewType->getRegParmType()
2603 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002604 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002605 return true;
2606 }
John McCall4f5019e2010-12-19 02:44:49 +00002607
2608 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2609 RequiresAdjustment = true;
2610 }
2611
Douglas Gregorf1404d72011-10-14 15:55:40 +00002612 // Merge ns_returns_retained attribute.
2613 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2614 if (NewTypeInfo.getProducesResult()) {
2615 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002616 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002617 return true;
2618 }
2619
2620 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2621 RequiresAdjustment = true;
2622 }
2623
John McCall4f5019e2010-12-19 02:44:49 +00002624 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002625 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2626 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2627 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002628 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002629 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002630 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002631
2632 // If this redeclaration makes the function inline, we may need to add it to
2633 // UndefinedButUsed.
2634 if (!Old->isInlined() && New->isInlined() &&
2635 !New->hasAttr<GNUInlineAttr>() &&
2636 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2637 Old->isUsed(false) &&
2638 !Old->isDefined() && !New->isThisDeclarationADefinition())
2639 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2640 SourceLocation()));
2641
2642 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2643 // about it.
2644 if (New->hasAttr<GNUInlineAttr>() &&
2645 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2646 UndefinedButUsed.erase(Old->getCanonicalDecl());
2647 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002648
David Blaikiebbafb8a2012-03-11 07:00:24 +00002649 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002650 // (C++98 13.1p2):
2651 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002652 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002653 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002654
2655 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002656 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002657 // Redeclarations or specializations of a function or function template
2658 // with a declared return type that uses a placeholder type shall also
2659 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002660 QualType OldDeclaredReturnType =
2661 (Old->getTypeSourceInfo()
2662 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2663 : OldType)->getReturnType();
2664 QualType NewDeclaredReturnType =
2665 (New->getTypeSourceInfo()
2666 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2667 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002668 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002669 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2670 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2671 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002672 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2673 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002674 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2675 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002676 if (New->isCXXClassMember() && New->isOutOfLine())
Alp Tokerd0787eb2014-07-02 01:47:15 +00002677 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2678 << New << New->getReturnTypeSourceRange();
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002679 else
Alp Tokerd0787eb2014-07-02 01:47:15 +00002680 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2681 << New->getReturnTypeSourceRange();
2682 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2683 << Old->getReturnTypeSourceRange();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002684 return true;
2685 }
2686 else
2687 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002688 }
2689
Alp Toker314cc812014-01-25 16:55:45 +00002690 QualType OldReturnType = OldType->getReturnType();
2691 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002692 if (OldReturnType != NewReturnType) {
2693 // If this function has a deduced return type and has already been
2694 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002695 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002696 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002697 New->setType(
2698 SubstAutoType(New->getType(),
2699 OldAT->isDependentType() ? Context.DependentTy
2700 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002701 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002702 SubstAutoType(NewQType,
2703 OldAT->isDependentType() ? Context.DependentTy
2704 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002705 }
2706 }
2707
2708 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2709 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002710 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002711 // Preserve triviality.
2712 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002713
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002714 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002715 // 2 CXXMethodDecls referring to the same function will be injected.
2716 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002717 bool IsClassScopeExplicitSpecialization =
2718 OldMethod->isFunctionTemplateSpecialization() &&
2719 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002720 bool isFriend = NewMethod->getFriendObjectKind();
2721
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002722 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2723 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002724 // -- Member function declarations with the same name and the
2725 // same parameter types cannot be overloaded if any of them
2726 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002727 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002728 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002729 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002730 return true;
2731 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002732
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002733 // C++ [class.mem]p1:
2734 // [...] A member shall not be declared twice in the
2735 // member-specification, except that a nested class or member
2736 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002737 if (ActiveTemplateInstantiations.empty()) {
2738 unsigned NewDiag;
2739 if (isa<CXXConstructorDecl>(OldMethod))
2740 NewDiag = diag::err_constructor_redeclared;
2741 else if (isa<CXXDestructorDecl>(NewMethod))
2742 NewDiag = diag::err_destructor_redeclared;
2743 else if (isa<CXXConversionDecl>(NewMethod))
2744 NewDiag = diag::err_conv_function_redeclared;
2745 else
2746 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002747
Richard Smith57e7ff92012-07-13 04:12:04 +00002748 Diag(New->getLocation(), NewDiag);
2749 } else {
2750 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2751 << New << New->getType();
2752 }
Richard Smithbdd14642014-02-04 01:14:30 +00002753 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002754
2755 // Complain if this is an explicit declaration of a special
2756 // member that was initially declared implicitly.
2757 //
2758 // As an exception, it's okay to befriend such methods in order
2759 // to permit the implicit constructor/destructor/operator calls.
2760 } else if (OldMethod->isImplicit()) {
2761 if (isFriend) {
2762 NewMethod->setImplicit();
2763 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002764 Diag(NewMethod->getLocation(),
2765 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002766 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002767 return true;
2768 }
Richard Smith337a5a12012-06-08 01:30:54 +00002769 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002770 Diag(NewMethod->getLocation(),
2771 diag::err_definition_of_explicitly_defaulted_member)
2772 << getSpecialMember(OldMethod);
2773 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002774 }
2775 }
2776
Richard Smith10876ef2013-01-17 01:30:42 +00002777 // C++11 [dcl.attr.noreturn]p1:
2778 // The first declaration of a function shall specify the noreturn
2779 // attribute if any declaration of that function specifies the noreturn
2780 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002781 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2782 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2783 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002784 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002785 diag::note_noreturn_missing_first_decl);
2786 }
2787
Richard Smithe233fbf2013-01-28 22:42:45 +00002788 // C++11 [dcl.attr.depend]p2:
2789 // The first declaration of a function shall specify the
2790 // carries_dependency attribute for its declarator-id if any declaration
2791 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002792 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2793 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2794 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002795 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002796 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002797 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2798 }
2799
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002800 // (C++98 8.3.5p3):
2801 // All declarations for a function shall agree exactly in both the
2802 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002803 // We also want to respect all the extended bits except noreturn.
2804
2805 // noreturn should now match unless the old type info didn't have it.
2806 QualType OldQTypeForComparison = OldQType;
2807 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2808 assert(OldQType == QualType(OldType, 0));
2809 const FunctionType *OldTypeForComparison
2810 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2811 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2812 assert(OldQTypeForComparison.isCanonical());
2813 }
2814
Rafael Espindolaf4187652013-02-14 01:18:37 +00002815 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002816 // As a special case, retain the language linkage from previous
2817 // declarations of a friend function as an extension.
2818 //
2819 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2820 // and is useful because there's otherwise no way to specify language
2821 // linkage within class scope.
2822 //
2823 // Check cautiously as the friend object kind isn't yet complete.
2824 if (New->getFriendObjectKind() != Decl::FOK_None) {
2825 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002826 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002827 } else {
2828 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002829 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002830 return true;
2831 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002832 }
2833
John McCall4f5019e2010-12-19 02:44:49 +00002834 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002835 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002836
Richard Smith541b38b2013-09-20 01:15:31 +00002837 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2838 New->isLocalExternDecl()) {
2839 // It's OK if we couldn't merge types for a local function declaraton
2840 // if either the old or new type is dependent. We'll merge the types
2841 // when we instantiate the function.
2842 return false;
2843 }
2844
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002845 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002846 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002847
2848 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002849 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002850 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002851 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002852 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2853 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Craig Topperc3ec1492014-05-26 06:22:03 +00002854 const FunctionProtoType *OldProto = nullptr;
Richard Smith1c34fb72013-08-13 18:18:50 +00002855 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002856 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002857 // The old declaration provided a function prototype, but the
2858 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002859 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002860 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
Alp Toker314cc812014-01-25 16:55:45 +00002861 NewQType =
2862 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2863 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002864 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002865 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002866
Alp Toker4284c6e2014-05-11 16:05:55 +00002867 // Synthesize parameters with the same types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002868 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002869 for (const auto &ParamType : OldProto->param_types()) {
2870 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002871 SourceLocation(), nullptr,
2872 ParamType, /*TInfo=*/nullptr,
2873 SC_None, nullptr);
John McCall8fb0d9d2011-05-01 22:35:37 +00002874 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002875 Param->setImplicit();
2876 Params.push_back(Param);
2877 }
2878
David Blaikie9c70e042011-09-21 18:16:56 +00002879 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002880 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002881
Richard Smith1c34fb72013-08-13 18:18:50 +00002882 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002883 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002884
Douglas Gregora74a2972009-03-06 22:43:54 +00002885 // GNU C permits a K&R definition to follow a prototype declaration
2886 // if the declared types of the parameters in the K&R definition
2887 // match the types in the prototype declaration, even when the
2888 // promoted types of the parameters from the K&R definition differ
2889 // from the types in the prototype. GCC then keeps the types from
2890 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002891 //
2892 // If a variadic prototype is followed by a non-variadic K&R definition,
2893 // the K&R definition becomes variadic. This is sort of an edge case, but
2894 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2895 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002896 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002897 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002898 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002899 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002900 SmallVector<QualType, 16> ArgTypes;
2901 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002902 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002903 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002904 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002905 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002906
Douglas Gregora74a2972009-03-06 22:43:54 +00002907 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002908 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2909 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002910 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002911 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002912 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002913 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2914 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002915 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002916 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002917 ArgTypes.push_back(NewParm->getType());
2918 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002919 NewParm->getType(),
2920 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002921 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2922 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002923 Warnings.push_back(Warn);
2924 ArgTypes.push_back(NewParm->getType());
2925 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002926 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002927 }
2928
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002929 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002930 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2931 Diag(Warnings[Warn].NewParm->getLocation(),
2932 diag::ext_param_promoted_not_compatible_with_prototype)
2933 << Warnings[Warn].PromotedType
2934 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002935 if (Warnings[Warn].OldParm->getLocation().isValid())
2936 Diag(Warnings[Warn].OldParm->getLocation(),
2937 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002938 }
2939
Richard Smith1c34fb72013-08-13 18:18:50 +00002940 if (MergeTypeWithOld)
2941 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2942 OldProto->getExtProtoInfo()));
2943 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002944 }
2945
2946 // Fall through to diagnose conflicting types.
2947 }
2948
John McCallad327cd2013-04-14 08:50:55 +00002949 // A function that has already been declared has been redeclared or
2950 // defined with a different type; show an appropriate diagnostic.
2951
2952 // If the previous declaration was an implicitly-generated builtin
2953 // declaration, then at the very least we should use a specialized note.
2954 unsigned BuiltinID;
2955 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2956 // If it's actually a library-defined builtin function like 'malloc'
2957 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002958 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002959 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002960 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002961 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002962
2963 // If this is a global redeclaration, just forget hereafter
2964 // about the "builtin-ness" of the function.
2965 //
2966 // Doing this for local extern declarations is problematic. If
2967 // the builtin declaration remains visible, a second invalid
2968 // local declaration will produce a hard error; if it doesn't
2969 // remain visible, a single bogus local redeclaration (which is
2970 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002971 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002972 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2973
Douglas Gregor893c2c92009-03-23 17:47:24 +00002974 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002975 }
Steve Naroff17832a42008-01-16 15:01:34 +00002976
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002977 PrevDiag = diag::note_previous_builtin_declaration;
2978 }
2979
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002980 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002981 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002982 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002983}
2984
Douglas Gregore62c0a42009-02-24 01:23:02 +00002985/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002986/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002987///
2988/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002989/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002990/// the new declaration, once we know that New is in fact a
2991/// redeclaration of Old.
2992///
2993/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002994bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002995 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002996 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002997 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002998
Douglas Gregore62c0a42009-02-24 01:23:02 +00002999 // Merge "pure" flag.
3000 if (Old->isPure())
3001 New->setPure();
3002
Rafael Espindolabefe1302012-11-25 14:07:59 +00003003 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003004 if (Old->getMostRecentDecl()->isUsed(false))
3005 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003006
John McCallf79e87d2011-03-02 04:00:57 +00003007 // Merge attributes from the parameters. These can mismatch with K&R
3008 // declarations.
3009 if (New->getNumParams() == Old->getNumParams())
3010 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
3011 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00003012 *this);
John McCallf79e87d2011-03-02 04:00:57 +00003013
David Blaikiebbafb8a2012-03-11 07:00:24 +00003014 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00003015 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00003016
Rafael Espindola8778c282012-11-29 16:09:03 +00003017 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00003018 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3019 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00003020 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00003021 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00003022 New->setType(Merged);
3023
Douglas Gregore62c0a42009-02-24 01:23:02 +00003024 return false;
3025}
3026
John McCall31168b02011-06-15 23:02:42 +00003027
John McCallf79e87d2011-03-02 04:00:57 +00003028void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00003029 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00003030
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00003031 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00003032 AvailabilityMergeKind MergeKind =
3033 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3034 : AMK_Override;
3035 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00003036
3037 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003038 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3039 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003040 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00003041 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003042 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00003043 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00003044
Douglas Gregor66a8ca02013-01-15 22:43:08 +00003045 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00003046}
3047
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003048/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3049/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00003050/// emitting diagnostics as appropriate.
3051///
3052/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00003053/// to here in AddInitializerToDecl. We can't check them before the initializer
3054/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00003055void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3056 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00003057 if (New->isInvalidDecl() || Old->isInvalidDecl())
3058 return;
3059
3060 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003061 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00003062 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00003063 // We don't know what the new type is until the initializer is attached.
3064 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003065 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3066 // These could still be something that needs exception specs checked.
3067 return MergeVarDeclExceptionSpecs(New, Old);
3068 }
Richard Smith30482bc2011-02-20 03:19:35 +00003069 // C++ [basic.link]p10:
3070 // [...] the types specified by all declarations referring to a given
3071 // object or function shall be identical, except that declarations for an
3072 // array object can specify array types that differ by the presence or
3073 // absence of a major array bound (8.3.4).
3074 else if (Old->getType()->isIncompleteArrayType() &&
3075 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003076 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3077 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3078 if (Context.hasSameType(OldArray->getElementType(),
3079 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00003080 MergedT = New->getType();
3081 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00003082 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003083 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3084 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3085 if (Context.hasSameType(OldArray->getElementType(),
3086 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00003087 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00003088 } else if (New->getType()->isObjCObjectPointerType() &&
3089 Old->getType()->isObjCObjectPointerType()) {
3090 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3091 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00003092 }
3093 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00003094 // C 6.2.7p2:
3095 // All declarations that refer to the same object or function shall have
3096 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00003097 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3098 }
3099 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003100 // It's OK if we couldn't merge types if either type is dependent, for a
3101 // block-scope variable. In other cases (static data members of class
3102 // templates, variable templates, ...), we require the types to be
3103 // equivalent.
3104 // FIXME: The C++ standard doesn't say anything about this.
3105 if ((New->getType()->isDependentType() ||
3106 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3107 // If the old type was dependent, we can't merge with it, so the new type
3108 // becomes dependent for now. We'll reproduce the original type when we
3109 // instantiate the TypeSourceInfo for the variable.
3110 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3111 New->setType(Context.DependentTy);
3112 return;
3113 }
3114
3115 // FIXME: Even if this merging succeeds, some other non-visible declaration
3116 // of this variable might have an incompatible type. For instance:
3117 //
3118 // extern int arr[];
3119 // void f() { extern int arr[2]; }
3120 // void g() { extern int arr[3]; }
3121 //
3122 // Neither C nor C++ requires a diagnostic for this, but we should still try
3123 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00003124 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00003125 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00003126 Diag(Old->getLocation(), diag::note_previous_definition);
3127 return New->setInvalidDecl();
3128 }
John McCallb65e8fe2013-04-01 18:34:28 +00003129
3130 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00003131 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00003132 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00003133 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00003134}
3135
Richard Smith3c785782013-09-03 21:00:58 +00003136static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3137 LookupResult &Previous) {
3138 // C11 6.2.7p4:
3139 // For an identifier with internal or external linkage declared
3140 // in a scope in which a prior declaration of that identifier is
3141 // visible, if the prior declaration specifies internal or
3142 // external linkage, the type of the identifier at the later
3143 // declaration becomes the composite type.
3144 //
3145 // If the variable isn't visible, we do not merge with its type.
3146 if (Previous.isShadowed())
3147 return false;
3148
3149 if (S.getLangOpts().CPlusPlus) {
3150 // C++11 [dcl.array]p3:
3151 // If there is a preceding declaration of the entity in the same
3152 // scope in which the bound was specified, an omitted array bound
3153 // is taken to be the same as in that earlier declaration.
3154 return NewVD->isPreviousDeclInSameBlockScope() ||
3155 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3156 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3157 } else {
3158 // If the old declaration was function-local, don't merge with its
3159 // type unless we're in the same function.
3160 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3161 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3162 }
3163}
3164
Chris Lattner01564d92007-01-27 19:27:06 +00003165/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3166/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3167/// situation, merging decls or emitting diagnostics as appropriate.
3168///
Mike Stump11289f42009-09-09 15:08:12 +00003169/// Tentative definition rules (C99 6.9.2p2) are checked by
3170/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00003171/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00003172///
Richard Smith3c785782013-09-03 21:00:58 +00003173void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00003174 // If the new decl is already invalid, don't do any other checking.
3175 if (New->isInvalidDecl())
3176 return;
Mike Stump11289f42009-09-09 15:08:12 +00003177
Richard Smithbeef3452014-01-16 23:39:20 +00003178 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3179
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003180 // Verify the old decl was also a variable or variable template.
Craig Topperc3ec1492014-05-26 06:22:03 +00003181 VarDecl *Old = nullptr;
3182 VarTemplateDecl *OldTemplate = nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00003183 if (Previous.isSingleResult()) {
3184 if (NewTemplate) {
3185 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003186 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00003187 } else
3188 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003189 }
3190 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003191 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003192 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003193 Diag(Previous.getRepresentativeDecl()->getLocation(),
3194 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003195 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003196 }
Chris Lattner84966392008-03-03 03:28:21 +00003197
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003198 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3199 return;
3200
Richard Smithbeef3452014-01-16 23:39:20 +00003201 // Ensure the template parameters are compatible.
3202 if (NewTemplate &&
3203 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3204 OldTemplate->getTemplateParameters(),
3205 /*Complain=*/true, TPL_TemplateMatch))
3206 return;
3207
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003208 // C++ [class.mem]p1:
3209 // A member shall not be declared twice in the member-specification [...]
3210 //
3211 // Here, we need only consider static data members.
3212 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3213 Diag(New->getLocation(), diag::err_duplicate_member)
3214 << New->getIdentifier();
3215 Diag(Old->getLocation(), diag::note_previous_declaration);
3216 New->setInvalidDecl();
3217 }
3218
Douglas Gregor32c17572012-01-01 20:30:41 +00003219 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003220 // Warn if an already-declared variable is made a weak_import in a subsequent
3221 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003222 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003223 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003224 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003225 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3226 Diag(Old->getLocation(), diag::note_previous_definition);
3227 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003228 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003229 }
Chris Lattner84966392008-03-03 03:28:21 +00003230
Richard Smith30482bc2011-02-20 03:19:35 +00003231 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003232 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3233
Richard Smith30482bc2011-02-20 03:19:35 +00003234 if (New->isInvalidDecl())
3235 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003236
David Majnemer5b63fa02014-06-18 23:26:25 +00003237 diag::kind PrevDiag;
3238 SourceLocation OldLocation;
3239 std::tie(PrevDiag, OldLocation) =
3240 getNoteDiagForInvalidRedeclaration(Old, New);
3241
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003242 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003243 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003244 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003245 Old->hasExternalFormalLinkage()) {
David Majnemer5b63fa02014-06-18 23:26:25 +00003246 if (getLangOpts().MicrosoftExt) {
3247 Diag(New->getLocation(), diag::ext_static_non_static)
3248 << New->getDeclName();
3249 Diag(OldLocation, PrevDiag);
3250 } else {
3251 Diag(New->getLocation(), diag::err_static_non_static)
3252 << New->getDeclName();
3253 Diag(OldLocation, PrevDiag);
3254 return New->setInvalidDecl();
3255 }
Steve Naroff1e787362008-01-30 00:44:01 +00003256 }
Mike Stump11289f42009-09-09 15:08:12 +00003257 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003258 // For an identifier declared with the storage-class specifier
3259 // extern in a scope in which a prior declaration of that
3260 // identifier is visible,23) if the prior declaration specifies
3261 // internal or external linkage, the linkage of the identifier at
3262 // the later declaration is the same as the linkage specified at
3263 // the prior declaration. If no prior declaration is visible, or
3264 // if the prior declaration specifies no linkage, then the
3265 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003266 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003267 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003268 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003269 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003270 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003271 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003272 Diag(OldLocation, PrevDiag);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003273 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003274 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003275
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003276 // Check if extern is followed by non-extern and vice-versa.
3277 if (New->hasExternalStorage() &&
3278 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3279 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003280 Diag(OldLocation, PrevDiag);
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003281 return New->setInvalidDecl();
3282 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003283 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3284 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003285 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003286 Diag(OldLocation, PrevDiag);
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003287 return New->setInvalidDecl();
3288 }
3289
Steve Naroffa5629372008-09-17 14:05:40 +00003290 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003291
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003292 // FIXME: The test for external storage here seems wrong? We still
3293 // need to check for mismatches.
3294 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003295 // Don't complain about out-of-line definitions of static members.
3296 !(Old->getLexicalDeclContext()->isRecord() &&
3297 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003298 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003299 Diag(OldLocation, PrevDiag);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003300 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003301 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003302
Richard Smithfd3834f2013-04-13 02:43:54 +00003303 if (New->getTLSKind() != Old->getTLSKind()) {
3304 if (!Old->getTLSKind()) {
3305 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003306 Diag(OldLocation, PrevDiag);
Richard Smithfd3834f2013-04-13 02:43:54 +00003307 } else if (!New->getTLSKind()) {
3308 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003309 Diag(OldLocation, PrevDiag);
Richard Smithfd3834f2013-04-13 02:43:54 +00003310 } else {
3311 // Do not allow redeclaration to change the variable between requiring
3312 // static and dynamic initialization.
3313 // FIXME: GCC allows this, but uses the TLS keyword on the first
3314 // declaration to determine the kind. Do we need to be compatible here?
3315 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3316 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
David Majnemer5b63fa02014-06-18 23:26:25 +00003317 Diag(OldLocation, PrevDiag);
Richard Smithfd3834f2013-04-13 02:43:54 +00003318 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003319 }
3320
Sebastian Redlf1842912010-02-02 18:35:11 +00003321 // C++ doesn't have tentative definitions, so go right ahead and check here.
3322 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003323 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003324 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003325 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003326 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003327 Diag(Def->getLocation(), diag::note_previous_definition);
3328 New->setInvalidDecl();
3329 return;
3330 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003331
Rafael Espindolaf4187652013-02-14 01:18:37 +00003332 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003333 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
David Majnemer5b63fa02014-06-18 23:26:25 +00003334 Diag(OldLocation, PrevDiag);
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003335 New->setInvalidDecl();
3336 return;
3337 }
3338
Rafael Espindolabefe1302012-11-25 14:07:59 +00003339 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003340 if (Old->getMostRecentDecl()->isUsed(false))
3341 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003342
Douglas Gregor0760fa12009-03-10 23:43:53 +00003343 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003344 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003345 if (NewTemplate)
3346 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003347
3348 // Inherit access appropriately.
3349 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003350 if (NewTemplate)
3351 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003352}
3353
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003354/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3355/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003356Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003357 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003358 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003359}
3360
David Majnemer2206bf52014-03-05 08:57:59 +00003361static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003362 if (!S.Context.getLangOpts().CPlusPlus)
3363 return;
3364
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003365 if (isa<CXXRecordDecl>(Tag->getParent())) {
3366 // If this tag is the direct child of a class, number it if
3367 // it is anonymous.
3368 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3369 return;
3370 MangleNumberingContext &MCtx =
3371 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003372 S.Context.setManglingNumber(
3373 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003374 return;
3375 }
3376
3377 // If this tag isn't a direct child of a class, number it if it is local.
3378 Decl *ManglingContextDecl;
3379 if (MangleNumberingContext *MCtx =
3380 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3381 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003382 S.Context.setManglingNumber(
3383 Tag,
3384 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003385 }
3386}
3387
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003388/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003389/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003390/// parameters to cope with template friend declarations.
3391Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3392 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003393 MultiTemplateParamsArg TemplateParams,
3394 bool IsExplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003395 Decl *TagD = nullptr;
3396 TagDecl *Tag = nullptr;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003397 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3398 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003399 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003400 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003401 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003402 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003403
3404 if (!TagD) // We probably had an error
Craig Topperc3ec1492014-05-26 06:22:03 +00003405 return nullptr;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003406
John McCall07e91c02009-08-06 02:15:43 +00003407 // Note that the above type specs guarantee that the
3408 // type rep is a Decl, whereas in many of the others
3409 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003410 if (isa<TagDecl>(TagD))
3411 Tag = cast<TagDecl>(TagD);
3412 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3413 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003414 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003415
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003416 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003417 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003418 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003419 if (Tag->isInvalidDecl())
3420 return Tag;
3421 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003422
Nuno Lopese9823fa2009-12-17 11:35:26 +00003423 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3424 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3425 // or incomplete types shall not be restrict-qualified."
3426 if (TypeQuals & DeclSpec::TQ_restrict)
3427 Diag(DS.getRestrictSpecLoc(),
3428 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3429 << DS.getSourceRange();
3430 }
3431
Richard Smitha77a0a62011-08-15 21:04:07 +00003432 if (DS.isConstexprSpecified()) {
3433 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3434 // and definitions of functions and variables.
3435 if (Tag)
3436 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3437 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3438 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003439 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3440 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003441 else
3442 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3443 // Don't emit warnings after this error.
3444 return TagD;
3445 }
3446
Richard Smithb1402ae2013-03-18 22:52:47 +00003447 DiagnoseFunctionSpecifiers(DS);
3448
Douglas Gregor3dad8422009-09-26 06:47:28 +00003449 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003450 // If we're dealing with a decl but not a TagDecl, assume that
3451 // whatever routines created it handled the friendship aspect.
3452 if (TagD && !Tag)
Craig Topperc3ec1492014-05-26 06:22:03 +00003453 return nullptr;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003454 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003455 }
John McCallaa017372011-03-22 23:00:04 +00003456
Richard Smithb1402ae2013-03-18 22:52:47 +00003457 CXXScopeSpec &SS = DS.getTypeSpecScope();
3458 bool IsExplicitSpecialization =
3459 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3460 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3461 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3462 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3463 // nested-name-specifier unless it is an explicit instantiation
3464 // or an explicit specialization.
3465 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3466 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3467 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3468 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3469 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3470 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3471 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00003472 return nullptr;
Richard Smithb1402ae2013-03-18 22:52:47 +00003473 }
3474
3475 // Track whether this decl-specifier declares anything.
3476 bool DeclaresAnything = true;
3477
3478 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003479 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003480 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003481 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003482 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003483 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003484 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003485
Richard Smithb1402ae2013-03-18 22:52:47 +00003486 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003487 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003488 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003489
David Majnemer8f0ed912014-08-11 07:29:54 +00003490 // C11 6.7.2.1p2:
3491 // A struct-declaration that does not declare an anonymous structure or
3492 // anonymous union shall contain a struct-declarator-list.
Richard Smith04d3b3e2014-08-26 21:51:57 +00003493 //
3494 // This rule also existed in C89 and C99; the grammar for struct-declaration
3495 // did not permit a struct-declaration without a struct-declarator-list.
Fariborz Jahanianffc120a2014-08-26 21:10:47 +00003496 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003497 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
David Majnemer8f0ed912014-08-11 07:29:54 +00003498 // Check for Microsoft C extension: anonymous struct/union member.
3499 // Handle 2 kinds of anonymous struct/union:
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003500 // struct STRUCT;
David Majnemer8f0ed912014-08-11 07:29:54 +00003501 // union UNION;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003502 // and
3503 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
David Majnemer8f0ed912014-08-11 07:29:54 +00003504 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3505 if ((Tag && Tag->getDeclName()) ||
3506 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3507 RecordDecl *Record = nullptr;
3508 if (Tag)
3509 Record = dyn_cast<RecordDecl>(Tag);
3510 else if (const RecordType *RT =
3511 DS.getRepAsType().get()->getAsStructureType())
3512 Record = RT->getDecl();
3513 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3514 Record = UT->getDecl();
3515
3516 if (Record && getLangOpts().MicrosoftExt) {
3517 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3518 << Record->isUnion() << DS.getSourceRange();
3519 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3520 }
3521
3522 DeclaresAnything = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003523 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003524 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003525
3526 // Skip all the checks below if we have a type error.
3527 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3528 (TagD && TagD->isInvalidDecl()))
3529 return TagD;
3530
3531 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003532 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3533 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3534 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003535 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3536 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003537
John McCallaa017372011-03-22 23:00:04 +00003538 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003539 // Customize diagnostic for a typedef missing a name.
3540 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003541 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003542 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003543 else
3544 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003545 }
Mike Stump11289f42009-09-09 15:08:12 +00003546
Richard Smithb1402ae2013-03-18 22:52:47 +00003547 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003548 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3549 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3550 << Tag->getTagKind()
3551 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3552
Richard Smithb1402ae2013-03-18 22:52:47 +00003553 ActOnDocumentableDecl(TagD);
3554
3555 // C 6.7/2:
3556 // A declaration [...] shall declare at least a declarator [...], a tag,
3557 // or the members of an enumeration.
3558 // C++ [dcl.dcl]p3:
3559 // [If there are no declarators], and except for the declaration of an
3560 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3561 // names into the program, or shall redeclare a name introduced by a
3562 // previous declaration.
3563 if (!DeclaresAnything) {
3564 // In C, we allow this as a (popular) extension / bug. Don't bother
3565 // producing further diagnostics for redundant qualifiers after this.
3566 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3567 return TagD;
3568 }
3569
3570 // C++ [dcl.stc]p1:
3571 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3572 // init-declarator-list of the declaration shall not be empty.
3573 // C++ [dcl.fct.spec]p1:
3574 // If a cv-qualifier appears in a decl-specifier-seq, the
3575 // init-declarator-list of the declaration shall not be empty.
3576 //
3577 // Spurious qualifiers here appear to be valid in C.
3578 unsigned DiagID = diag::warn_standalone_specifier;
3579 if (getLangOpts().CPlusPlus)
3580 DiagID = diag::ext_standalone_specifier;
3581
3582 // Note that a linkage-specification sets a storage class, but
3583 // 'extern "C" struct foo;' is actually valid and not theoretically
3584 // useless.
Aaron Ballman5a1ef6b2014-05-26 17:03:54 +00003585 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3586 if (SCS == DeclSpec::SCS_mutable)
3587 // Since mutable is not a viable storage class specifier in C, there is
3588 // no reason to treat it as an extension. Instead, diagnose as an error.
3589 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3590 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
Richard Smithb1402ae2013-03-18 22:52:47 +00003591 Diag(DS.getStorageClassSpecLoc(), DiagID)
3592 << DeclSpec::getSpecifierName(SCS);
Aaron Ballman5a1ef6b2014-05-26 17:03:54 +00003593 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003594
Richard Smithb4a9e862013-04-12 22:46:28 +00003595 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3596 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3597 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003598 if (DS.getTypeQualifiers()) {
3599 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3600 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3601 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3602 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3603 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003604 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3605 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003606 }
3607
Eli Friedmane3217952011-12-17 00:36:09 +00003608 // Warn about ignored type attributes, for example:
3609 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003610 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003611 if (!DS.getAttributes().empty()) {
3612 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3613 if (TypeSpecType == DeclSpec::TST_class ||
3614 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003615 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003616 TypeSpecType == DeclSpec::TST_union ||
3617 TypeSpecType == DeclSpec::TST_enum) {
3618 AttributeList* attrs = DS.getAttributes().getList();
3619 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003620 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003621 << attrs->getName()
3622 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3623 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003624 TypeSpecType == DeclSpec::TST_union ? 2 :
3625 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003626 attrs = attrs->getNext();
3627 }
3628 }
3629 }
John McCallaa017372011-03-22 23:00:04 +00003630
John McCall48871652010-08-21 09:40:31 +00003631 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003632}
3633
John McCallea305ed2009-12-18 10:40:03 +00003634/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003635/// check if there's an existing declaration that can't be overloaded.
3636///
3637/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003638static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3639 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003640 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003641 DeclarationName Name,
3642 SourceLocation NameLoc,
3643 unsigned diagnostic) {
3644 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3645 Sema::ForRedeclaration);
3646 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003647
John McCallea305ed2009-12-18 10:40:03 +00003648 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003649 return false;
3650
3651 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003652 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003653 assert(PrevDecl && "Expected a non-null Decl");
3654
3655 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3656 return false;
John McCall1f82f242009-11-18 22:49:29 +00003657
John McCallea305ed2009-12-18 10:40:03 +00003658 SemaRef.Diag(NameLoc, diagnostic) << Name;
3659 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003660
3661 return true;
3662}
3663
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003664/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3665/// anonymous struct or union AnonRecord into the owning context Owner
3666/// and scope S. This routine will be invoked just after we realize
3667/// that an unnamed union or struct is actually an anonymous union or
3668/// struct, e.g.,
3669///
3670/// @code
3671/// union {
3672/// int i;
3673/// float f;
3674/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3675/// // f into the surrounding scope.x
3676/// @endcode
3677///
3678/// This routine is recursive, injecting the names of nested anonymous
3679/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003680static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003681 DeclContext *Owner,
3682 RecordDecl *AnonRecord,
3683 AccessSpecifier AS,
3684 SmallVectorImpl<NamedDecl *> &Chaining,
3685 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003686 unsigned diagKind
3687 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3688 : diag::err_anonymous_struct_member_redecl;
3689
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003690 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003691
3692 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003693 for (auto *D : AnonRecord->decls()) {
3694 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3695 cast<NamedDecl>(D)->getDeclName()) {
3696 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003697 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3698 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003699 // C++ [class.union]p2:
3700 // The names of the members of an anonymous union shall be
3701 // distinct from the names of any other entity in the
3702 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003703 Invalid = true;
3704 } else {
3705 // C++ [class.union]p2:
3706 // For the purpose of name lookup, after the anonymous union
3707 // definition, the members of the anonymous union are
3708 // considered to have been defined in the scope in which the
3709 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003710 unsigned OldChainingSize = Chaining.size();
3711 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003712 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003713 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003714 else
3715 Chaining.push_back(VD);
3716
Francois Pichet783dd6e2010-11-21 06:08:52 +00003717 assert(Chaining.size() >= 2);
3718 NamedDecl **NamedChain =
3719 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3720 for (unsigned i = 0; i < Chaining.size(); i++)
3721 NamedChain[i] = Chaining[i];
3722
3723 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003724 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3725 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003726 NamedChain, Chaining.size());
3727
3728 IndirectField->setAccess(AS);
3729 IndirectField->setImplicit();
3730 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003731
3732 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003733 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003734
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003735 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003736 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003737 }
3738 }
3739
3740 return Invalid;
3741}
3742
Douglas Gregorc4df4072010-04-19 22:54:31 +00003743/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3744/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003745/// illegal input values are mapped to SC_None.
3746static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003747StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3748 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3749 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3750 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003751 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003752 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003753 case DeclSpec::SCS_extern:
3754 if (DS.isExternInLinkageSpec())
3755 return SC_None;
3756 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003757 case DeclSpec::SCS_static: return SC_Static;
3758 case DeclSpec::SCS_auto: return SC_Auto;
3759 case DeclSpec::SCS_register: return SC_Register;
3760 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003761 // Illegal SCSs map to None: error reporting is up to the caller.
3762 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003763 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003764 }
3765 llvm_unreachable("unknown storage class specifier");
3766}
3767
Richard Smithab44d5b2013-12-10 08:25:00 +00003768static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3769 assert(Record->hasInClassInitializer());
3770
Aaron Ballman629afae2014-03-07 19:56:05 +00003771 for (const auto *I : Record->decls()) {
3772 const auto *FD = dyn_cast<FieldDecl>(I);
3773 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003774 FD = IFD->getAnonField();
3775 if (FD && FD->hasInClassInitializer())
3776 return FD->getLocation();
3777 }
3778
3779 llvm_unreachable("couldn't find in-class initializer");
3780}
3781
3782static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3783 SourceLocation DefaultInitLoc) {
3784 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3785 return;
3786
3787 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3788 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3789}
3790
3791static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3792 CXXRecordDecl *AnonUnion) {
3793 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3794 return;
3795
3796 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3797}
3798
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003799/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003800/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003801/// (C++ [class.union]) and a C11 feature; anonymous structures
3802/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003803Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003804 AccessSpecifier AS,
3805 RecordDecl *Record,
3806 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003807 DeclContext *Owner = Record->getDeclContext();
3808
3809 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003810 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003811 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003812 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003813 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003814 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003815 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003816
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003817 // C and C++ require different kinds of checks for anonymous
3818 // structs/unions.
3819 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003820 if (getLangOpts().CPlusPlus) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003821 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00003822 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003823 if (Record->isUnion()) {
3824 // C++ [class.union]p6:
3825 // Anonymous unions declared in a named namespace or in the
3826 // global namespace shall be declared static.
3827 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3828 (isa<TranslationUnitDecl>(Owner) ||
3829 (isa<NamespaceDecl>(Owner) &&
3830 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003831 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3832 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003833
3834 // Recover by adding 'static'.
3835 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003836 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003837 }
3838 // C++ [class.union]p6:
3839 // A storage class is not allowed in a declaration of an
3840 // anonymous union in a class scope.
3841 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3842 isa<RecordDecl>(Owner)) {
3843 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003844 diag::err_anonymous_union_with_storage_spec)
3845 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003846
3847 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003848 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3849 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003850 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003851 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003852 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003853
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003854 // Ignore const/volatile/restrict qualifiers.
3855 if (DS.getTypeQualifiers()) {
3856 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3857 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003858 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003859 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3860 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003861 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003862 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003863 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003864 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3865 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003866 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003867 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003868 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003869 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003870 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3871 Diag(DS.getAtomicSpecLoc(),
3872 diag::ext_anonymous_struct_union_qualified)
3873 << Record->isUnion() << "_Atomic"
3874 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003875
3876 DS.ClearTypeQualifiers();
3877 }
3878
Mike Stump11289f42009-09-09 15:08:12 +00003879 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003880 // The member-specification of an anonymous union shall only
3881 // define non-static data members. [Note: nested types and
3882 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003883 for (auto *Mem : Record->decls()) {
3884 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003885 // C++ [class.union]p3:
3886 // An anonymous union shall not have private or protected
3887 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003888 assert(FD->getAccess() != AS_none);
3889 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003890 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3891 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3892 Invalid = true;
3893 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003894
Alexis Hunt97ab5542011-05-16 22:41:40 +00003895 // C++ [class.union]p1
3896 // An object of a class with a non-trivial constructor, a non-trivial
3897 // copy constructor, a non-trivial destructor, or a non-trivial copy
3898 // assignment operator cannot be a member of a union, nor can an
3899 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003900 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003901 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003902 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003903 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003904 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003905 // This is a type that showed up in an
3906 // elaborated-type-specifier inside the anonymous struct or
3907 // union, but which actually declares a type outside of the
3908 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003909 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003910 if (!MemRecord->isAnonymousStructOrUnion() &&
3911 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003912 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003913 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003914 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3915 << (int)Record->isUnion();
3916 else {
3917 // This is a nested type declaration.
3918 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3919 << (int)Record->isUnion();
3920 Invalid = true;
3921 }
Richard Smith254d2662013-01-28 00:54:05 +00003922 } else {
3923 // This is an anonymous type definition within another anonymous type.
3924 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3925 // not part of standard C++.
3926 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003927 diag::ext_anonymous_record_with_anonymous_type)
3928 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003929 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003930 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003931 // Any access specifier is fine.
Aaron Ballmanf93ef4e2014-06-24 16:22:41 +00003932 } else if (isa<StaticAssertDecl>(Mem)) {
3933 // In C++1z, static_assert declarations are also fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003934 } else {
3935 // We have something that isn't a non-static data
3936 // member. Complain about it.
3937 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003938 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003939 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003940 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003941 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003942 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003943 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003944
3945 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003946 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003947 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003948 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003949 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003950 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003951 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003952 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003953 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003954 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003955 }
3956 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003957
3958 // C++11 [class.union]p8 (DR1460):
3959 // At most one variant member of a union may have a
3960 // brace-or-equal-initializer.
3961 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3962 Owner->isRecord())
3963 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3964 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003965 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003966
3967 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003968 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003969 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003970 Invalid = true;
3971 }
3972
John McCallfa2d6922009-10-22 23:31:08 +00003973 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003974 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003975 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003976 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003977
Mike Stump11289f42009-09-09 15:08:12 +00003978 // Create a declaration for this anonymous struct/union.
Craig Topperc3ec1492014-05-26 06:22:03 +00003979 NamedDecl *Anon = nullptr;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003980 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003981 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003982 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003983 Record->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003984 /*IdentifierInfo=*/nullptr,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003985 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003986 TInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00003987 /*BitWidth=*/nullptr, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003988 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003989 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003990 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003991 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003992 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003993 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003994 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003995 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003996 // mutable can only appear on non-static class members, so it's always
3997 // an error here
3998 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3999 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00004000 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004001 }
4002
Abramo Bagnaradff19302011-03-08 08:55:46 +00004003 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004004 DS.getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004005 Record->getLocation(), /*IdentifierInfo=*/nullptr,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004006 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004007 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00004008
4009 // Default-initialize the implicit variable. This initialization will be
4010 // trivial in almost all cases, except if a union member has an in-class
4011 // initializer:
4012 // union { int n = 0; };
4013 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004014 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00004015 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004016
Richard Smithab44d5b2013-12-10 08:25:00 +00004017 // Mark this as an anonymous struct/union type.
4018 Record->setAnonymousStructOrUnion(true);
4019
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004020 // Add the anonymous struct/union object to the current
4021 // context. We'll be referencing this object when we refer to one of
4022 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004023 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00004024
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004025 // Inject the members of the anonymous struct/union into the owning
4026 // context and into the identifier resolver chain for name lookup
4027 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004028 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004029 Chain.push_back(Anon);
4030
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004031 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4032 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004033 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004034
David Majnemer2206bf52014-03-05 08:57:59 +00004035 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4036 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4037 Decl *ManglingContextDecl;
4038 if (MangleNumberingContext *MCtx =
4039 getCurrentMangleNumberContext(NewVD->getDeclContext(),
4040 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00004041 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00004042 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4043 }
4044 }
4045 }
4046
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004047 if (Invalid)
4048 Anon->setInvalidDecl();
4049
John McCall48871652010-08-21 09:40:31 +00004050 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00004051}
4052
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004053/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4054/// Microsoft C anonymous structure.
4055/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4056/// Example:
4057///
4058/// struct A { int a; };
4059/// struct B { struct A; int b; };
4060///
4061/// void foo() {
4062/// B var;
David Majnemer8f0ed912014-08-11 07:29:54 +00004063/// var.a = 3;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004064/// }
4065///
4066Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4067 RecordDecl *Record) {
David Majnemer8f0ed912014-08-11 07:29:54 +00004068 assert(Record && "expected a record!");
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004069
4070 // Mock up a declarator.
4071 Declarator Dc(DS, Declarator::TypeNameContext);
4072 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4073 assert(TInfo && "couldn't build declarator info for anonymous struct");
4074
David Majnemerd8e366b2014-09-18 00:42:05 +00004075 auto *ParentDecl = cast<RecordDecl>(CurContext);
4076 QualType RecTy = Context.getTypeDeclType(Record);
4077
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004078 // Create a declaration for this anonymous struct.
Craig Topperc3ec1492014-05-26 06:22:03 +00004079 NamedDecl *Anon = FieldDecl::Create(Context,
David Majnemerd8e366b2014-09-18 00:42:05 +00004080 ParentDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004081 DS.getLocStart(),
4082 DS.getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004083 /*IdentifierInfo=*/nullptr,
David Majnemerd8e366b2014-09-18 00:42:05 +00004084 RecTy,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004085 TInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00004086 /*BitWidth=*/nullptr, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004087 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004088 Anon->setImplicit();
4089
4090 // Add the anonymous struct object to the current context.
4091 CurContext->addDecl(Anon);
4092
4093 // Inject the members of the anonymous struct into the current
4094 // context and into the identifier resolver chain for name lookup
4095 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004096 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004097 Chain.push_back(Anon);
4098
Nico Weberf8bb3de2012-02-01 00:41:00 +00004099 RecordDecl *RecordDef = Record->getDefinition();
David Majnemerd8e366b2014-09-18 00:42:05 +00004100 if (RequireCompleteType(Anon->getLocation(), RecTy,
4101 diag::err_field_incomplete) ||
4102 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4103 AS_none, Chain, true)) {
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004104 Anon->setInvalidDecl();
David Majnemerd8e366b2014-09-18 00:42:05 +00004105 ParentDecl->setInvalidDecl();
4106 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00004107
4108 return Anon;
4109}
Steve Naroff2fea1392007-09-02 02:04:30 +00004110
Douglas Gregor92751d42008-11-17 22:58:34 +00004111/// GetNameForDeclarator - Determine the full declaration name for the
4112/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004113DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00004114 return GetNameFromUnqualifiedId(D.getName());
4115}
4116
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004117/// \brief Retrieves the declaration name from a parsed unqualified-id.
4118DeclarationNameInfo
4119Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4120 DeclarationNameInfo NameInfo;
4121 NameInfo.setLoc(Name.StartLocation);
4122
Douglas Gregor7861a802009-11-03 01:35:08 +00004123 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00004124
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00004125 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004126 case UnqualifiedId::IK_Identifier:
4127 NameInfo.setName(Name.Identifier);
4128 NameInfo.setLoc(Name.StartLocation);
4129 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00004130
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004131 case UnqualifiedId::IK_OperatorFunctionId:
4132 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4133 Name.OperatorFunctionId.Operator));
4134 NameInfo.setLoc(Name.StartLocation);
4135 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4136 = Name.OperatorFunctionId.SymbolLocations[0];
4137 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4138 = Name.EndLocation.getRawEncoding();
4139 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004140
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004141 case UnqualifiedId::IK_LiteralOperatorId:
4142 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4143 Name.Identifier));
4144 NameInfo.setLoc(Name.StartLocation);
4145 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4146 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004147
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004148 case UnqualifiedId::IK_ConversionFunctionId: {
4149 TypeSourceInfo *TInfo;
4150 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4151 if (Ty.isNull())
4152 return DeclarationNameInfo();
4153 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4154 Context.getCanonicalType(Ty)));
4155 NameInfo.setLoc(Name.StartLocation);
4156 NameInfo.setNamedTypeInfo(TInfo);
4157 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00004158 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004159
4160 case UnqualifiedId::IK_ConstructorName: {
4161 TypeSourceInfo *TInfo;
4162 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4163 if (Ty.isNull())
4164 return DeclarationNameInfo();
4165 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4166 Context.getCanonicalType(Ty)));
4167 NameInfo.setLoc(Name.StartLocation);
4168 NameInfo.setNamedTypeInfo(TInfo);
4169 return NameInfo;
4170 }
4171
4172 case UnqualifiedId::IK_ConstructorTemplateId: {
4173 // In well-formed code, we can only have a constructor
4174 // template-id that refers to the current context, so go there
4175 // to find the actual type being constructed.
4176 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4177 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4178 return DeclarationNameInfo();
4179
4180 // Determine the type of the class being constructed.
4181 QualType CurClassType = Context.getTypeDeclType(CurClass);
4182
4183 // FIXME: Check two things: that the template-id names the same type as
4184 // CurClassType, and that the template-id does not occur when the name
4185 // was qualified.
4186
4187 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4188 Context.getCanonicalType(CurClassType)));
4189 NameInfo.setLoc(Name.StartLocation);
4190 // FIXME: should we retrieve TypeSourceInfo?
Craig Topperc3ec1492014-05-26 06:22:03 +00004191 NameInfo.setNamedTypeInfo(nullptr);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004192 return NameInfo;
4193 }
4194
4195 case UnqualifiedId::IK_DestructorName: {
4196 TypeSourceInfo *TInfo;
4197 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4198 if (Ty.isNull())
4199 return DeclarationNameInfo();
4200 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4201 Context.getCanonicalType(Ty)));
4202 NameInfo.setLoc(Name.StartLocation);
4203 NameInfo.setNamedTypeInfo(TInfo);
4204 return NameInfo;
4205 }
4206
4207 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00004208 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004209 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4210 return Context.getNameForTemplate(TName, TNameLoc);
4211 }
4212
4213 } // switch (Name.getKind())
4214
David Blaikie83d382b2011-09-23 05:06:16 +00004215 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00004216}
4217
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004218static QualType getCoreType(QualType Ty) {
4219 do {
4220 if (Ty->isPointerType() || Ty->isReferenceType())
4221 Ty = Ty->getPointeeType();
4222 else if (Ty->isArrayType())
4223 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4224 else
4225 return Ty.withoutLocalFastQualifiers();
4226 } while (true);
4227}
4228
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004229/// hasSimilarParameters - Determine whether the C++ functions Declaration
4230/// and Definition have "nearly" matching parameters. This heuristic is
4231/// used to improve diagnostics in the case where an out-of-line function
4232/// definition doesn't match any declaration within the class or namespace.
4233/// Also sets Params to the list of indices to the parameters that differ
4234/// between the declaration and the definition. If hasSimilarParameters
4235/// returns true and Params is empty, then all of the parameters match.
4236static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00004237 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004238 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004239 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004240 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00004241 if (Declaration->param_size() != Definition->param_size())
4242 return false;
4243 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4244 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4245 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4246
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004247 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004248 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004249 continue;
4250
4251 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4252 QualType DefParamBaseTy = getCoreType(DefParamTy);
4253 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4254 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4255
4256 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4257 (DeclTyName && DeclTyName == DefTyName))
4258 Params.push_back(Idx);
4259 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004260 return false;
4261 }
4262
4263 return true;
4264}
4265
John McCall99b2fe52010-04-29 23:50:39 +00004266/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4267/// declarator needs to be rebuilt in the current instantiation.
4268/// Any bits of declarator which appear before the name are valid for
4269/// consideration here. That's specifically the type in the decl spec
4270/// and the base type in any member-pointer chunks.
4271static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4272 DeclarationName Name) {
4273 // The types we specifically need to rebuild are:
4274 // - typenames, typeofs, and decltypes
4275 // - types which will become injected class names
4276 // Of course, we also need to rebuild any type referencing such a
4277 // type. It's safest to just say "dependent", but we call out a
4278 // few cases here.
4279
4280 DeclSpec &DS = D.getMutableDeclSpec();
4281 switch (DS.getTypeSpecType()) {
4282 case DeclSpec::TST_typename:
4283 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004284 case DeclSpec::TST_underlyingType:
4285 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004286 // Grab the type from the parser.
Craig Topperc3ec1492014-05-26 06:22:03 +00004287 TypeSourceInfo *TSI = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00004288 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004289 if (T.isNull() || !T->isDependentType()) break;
4290
4291 // Make sure there's a type source info. This isn't really much
4292 // of a waste; most dependent types should have type source info
4293 // attached already.
4294 if (!TSI)
4295 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4296
4297 // Rebuild the type in the current instantiation.
4298 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4299 if (!TSI) return true;
4300
4301 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004302 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4303 DS.UpdateTypeRep(LocType);
4304 break;
4305 }
4306
Richard Smith1620ebd2012-10-01 20:35:07 +00004307 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004308 case DeclSpec::TST_typeofExpr: {
4309 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004310 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004311 if (Result.isInvalid()) return true;
4312 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004313 break;
4314 }
4315
4316 default:
4317 // Nothing to do for these decl specs.
4318 break;
4319 }
4320
4321 // It doesn't matter what order we do this in.
4322 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4323 DeclaratorChunk &Chunk = D.getTypeObject(I);
4324
4325 // The only type information in the declarator which can come
4326 // before the declaration name is the base type of a member
4327 // pointer.
4328 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4329 continue;
4330
4331 // Rebuild the scope specifier in-place.
4332 CXXScopeSpec &SS = Chunk.Mem.Scope();
4333 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4334 return true;
4335 }
4336
4337 return false;
4338}
4339
Anders Carlsson1052fd72011-07-04 16:28:17 +00004340Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004341 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004342 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004343
4344 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004345 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004346 Dcl->setTopLevelDeclInObjCContainer();
4347
4348 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004349}
4350
Richard Smithdda56e42011-04-15 14:24:37 +00004351/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4352/// If T is the name of a class, then each of the following shall have a
4353/// name different from T:
4354/// - every static data member of class T;
4355/// - every member function of class T
4356/// - every member of class T that is itself a type;
4357/// \returns true if the declaration name violates these rules.
4358bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4359 DeclarationNameInfo NameInfo) {
4360 DeclarationName Name = NameInfo.getName();
4361
4362 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4363 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4364 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4365 return true;
4366 }
4367
4368 return false;
4369}
Douglas Gregor31feb332012-03-17 23:06:31 +00004370
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004371/// \brief Diagnose a declaration whose declarator-id has the given
4372/// nested-name-specifier.
4373///
4374/// \param SS The nested-name-specifier of the declarator-id.
4375///
4376/// \param DC The declaration context to which the nested-name-specifier
4377/// resolves.
4378///
4379/// \param Name The name of the entity being declared.
4380///
4381/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004382///
4383/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004384bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004385 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004386 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004387 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004388 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004389 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004390
4391 // If the user provided a superfluous scope specifier that refers back to the
4392 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004393 //
4394 // class X {
4395 // void X::f();
4396 // };
Richard Smitha2302242013-12-05 07:51:02 +00004397 //
4398 // Note, it was once ill-formed to give redundant qualification in all
4399 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004400 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004401 if (Cur->isRecord()) {
4402 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4403 : diag::err_member_extra_qualification)
4404 << Name << FixItHint::CreateRemoval(SS.getRange());
4405 SS.clear();
4406 } else {
4407 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4408 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004409 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004410 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004411
4412 // Check whether the qualifying scope encloses the scope of the original
4413 // declaration.
4414 if (!Cur->Encloses(DC)) {
4415 if (Cur->isRecord())
4416 Diag(Loc, diag::err_member_qualification)
4417 << Name << SS.getRange();
4418 else if (isa<TranslationUnitDecl>(DC))
4419 Diag(Loc, diag::err_invalid_declarator_global_scope)
4420 << Name << SS.getRange();
4421 else if (isa<FunctionDecl>(Cur))
4422 Diag(Loc, diag::err_invalid_declarator_in_function)
4423 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004424 else if (isa<BlockDecl>(Cur))
4425 Diag(Loc, diag::err_invalid_declarator_in_block)
4426 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004427 else
4428 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004429 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004430
Douglas Gregor31feb332012-03-17 23:06:31 +00004431 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004432 }
4433
4434 if (Cur->isRecord()) {
4435 // Cannot qualify members within a class.
4436 Diag(Loc, diag::err_member_qualification)
4437 << Name << SS.getRange();
4438 SS.clear();
4439
4440 // C++ constructors and destructors with incorrect scopes can break
4441 // our AST invariants by having the wrong underlying types. If
4442 // that's the case, then drop this declaration entirely.
4443 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4444 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4445 !Context.hasSameType(Name.getCXXNameType(),
4446 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4447 return true;
4448
4449 return false;
4450 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004451
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004452 // C++11 [dcl.meaning]p1:
4453 // [...] "The nested-name-specifier of the qualified declarator-id shall
4454 // not begin with a decltype-specifer"
4455 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4456 while (SpecLoc.getPrefix())
4457 SpecLoc = SpecLoc.getPrefix();
4458 if (dyn_cast_or_null<DecltypeType>(
4459 SpecLoc.getNestedNameSpecifier()->getAsType()))
4460 Diag(Loc, diag::err_decltype_in_declarator)
4461 << SpecLoc.getTypeLoc().getSourceRange();
4462
Douglas Gregor31feb332012-03-17 23:06:31 +00004463 return false;
4464}
4465
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004466NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4467 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004468 // TODO: consider using NameInfo for diagnostic.
4469 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4470 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004471
Chris Lattner02c04392007-07-25 00:24:17 +00004472 // All of these full declarators require an identifier. If it doesn't have
4473 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004474 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004475 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004476 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004477 diag::err_declarator_need_ident)
4478 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004479 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00004480 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
Craig Topperc3ec1492014-05-26 06:22:03 +00004481 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004482
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004483 // The scope passed in may not be a decl scope. Zip up the scope tree until
4484 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004485 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004486 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004487 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004488
John McCall99b2fe52010-04-29 23:50:39 +00004489 DeclContext *DC = CurContext;
4490 if (D.getCXXScopeSpec().isInvalid())
4491 D.setInvalidType();
4492 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004493 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4494 UPPC_DeclarationQualifier))
Craig Topperc3ec1492014-05-26 06:22:03 +00004495 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +00004496
John McCall99b2fe52010-04-29 23:50:39 +00004497 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4498 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004499 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004500 // If we could not compute the declaration context, it's because the
4501 // declaration context is dependent but does not refer to a class,
4502 // class template, or class template partial specialization. Complain
4503 // and return early, to avoid the coming semantic disaster.
4504 Diag(D.getIdentifierLoc(),
4505 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004506 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004507 << D.getCXXScopeSpec().getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004508 return nullptr;
John McCall99b2fe52010-04-29 23:50:39 +00004509 }
John McCall99b2fe52010-04-29 23:50:39 +00004510 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004511
John McCall99b2fe52010-04-29 23:50:39 +00004512 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004513 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00004514 return nullptr;
John McCall99b2fe52010-04-29 23:50:39 +00004515
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004516 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4517 Diag(D.getIdentifierLoc(),
4518 diag::err_member_def_undefined_record)
4519 << Name << DC << D.getCXXScopeSpec().getRange();
4520 D.setInvalidType();
4521 } else if (!D.getDeclSpec().isFriendSpecified()) {
4522 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4523 Name, D.getIdentifierLoc())) {
4524 if (DC->isRecord())
Craig Topperc3ec1492014-05-26 06:22:03 +00004525 return nullptr;
4526
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004527 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004528 }
John McCall99b2fe52010-04-29 23:50:39 +00004529 }
4530
4531 // Check whether we need to rebuild the type of the given
4532 // declaration in the current instantiation.
4533 if (EnteringContext && IsDependentContext &&
4534 TemplateParamLists.size() != 0) {
4535 ContextRAII SavedContext(*this, DC);
4536 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4537 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004538 }
4539 }
Richard Smithdda56e42011-04-15 14:24:37 +00004540
4541 if (DiagnoseClassNameShadow(DC, NameInfo))
4542 // If this is a typedef, we'll end up spewing multiple diagnostics.
4543 // Just return early; it's safer.
4544 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
Craig Topperc3ec1492014-05-26 06:22:03 +00004545 return nullptr;
4546
John McCall8cb7bdf2010-06-04 23:28:52 +00004547 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4548 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004549
Douglas Gregor506bd562010-12-13 22:49:22 +00004550 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4551 UPPC_DeclarationType))
4552 D.setInvalidType();
4553
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004554 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004555 ForRedeclaration);
4556
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004557 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004558 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004559 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004560 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004561
4562 // If the declaration we're planning to build will be a function
4563 // or object with linkage, then look for another declaration with
4564 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004565 //
4566 // If the declaration we're planning to build will be declared with
4567 // external linkage in the translation unit, create any builtin with
4568 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004569 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4570 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004571 else if (CurContext->isFunctionOrMethod() &&
4572 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4573 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004574 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004575 CreateBuiltins =
4576 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4577 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4578 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4579 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004580
4581 if (IsLinkageLookup)
4582 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004583
Richard Smith1c34fb72013-08-13 18:18:50 +00004584 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004585 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004586 LookupQualifiedName(Previous, DC);
4587
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004588 // C++ [dcl.meaning]p1:
4589 // When the declarator-id is qualified, the declaration shall refer to a
4590 // previously declared member of the class or namespace to which the
4591 // qualifier refers (or, in the case of a namespace, of an element of the
4592 // inline namespace set of that namespace (7.3.1)) or to a specialization
4593 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004594 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004595 // Note that we already checked the context above, and that we do not have
4596 // enough information to make sure that Previous contains the declaration
4597 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004598 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004599 // class X {
4600 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004601 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004602 // };
4603 //
Douglas Gregorad590502008-12-15 23:53:10 +00004604 // void X::f(int) { } // ill-formed
4605 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004606 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004607 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004608 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004609
4610 // C++ [dcl.meaning]p1:
4611 // [...] the member shall not merely have been introduced by a
4612 // using-declaration in the scope of the class or namespace nominated by
4613 // the nested-name-specifier of the declarator-id.
4614 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004615 }
4616
John McCall1f82f242009-11-18 22:49:29 +00004617 if (Previous.isSingleResult() &&
4618 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004619 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004620 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004621 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4622 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004623
Douglas Gregor5101c242008-12-05 18:15:24 +00004624 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004625 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004626 }
4627
Douglas Gregor83a586e2008-04-13 21:07:44 +00004628 // In C++, the previous declaration we find might be a tag type
4629 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004630 // tag type. Note that this does does not apply if we're declaring a
4631 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004632 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004633 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004634 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004635
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004636 // Check that there are no default arguments other than in the parameters
4637 // of a function declaration (C++ only).
4638 if (getLangOpts().CPlusPlus)
4639 CheckExtraCXXDefaultArguments(D);
4640
Nico Webercb4c7f42012-12-23 00:40:46 +00004641 NamedDecl *New;
4642
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004643 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004644 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004645 if (TemplateParamLists.size()) {
4646 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
Craig Topperc3ec1492014-05-26 06:22:03 +00004647 return nullptr;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004648 }
Mike Stump11289f42009-09-09 15:08:12 +00004649
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004650 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004651 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004652 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004653 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004654 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004655 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004656 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4657 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004658 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004659
Craig Topperc3ec1492014-05-26 06:22:03 +00004660 if (!New)
4661 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004662
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004663 // If this has an identifier and is not an invalid redeclaration or
4664 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004665 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004666 !(D.isRedeclaration() && New->isInvalidDecl())) {
4667 // Only make a locally-scoped extern declaration visible if it is the first
4668 // declaration of this entity. Qualified lookup for such an entity should
4669 // only find this declaration if there is no visible declaration of it.
4670 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4671 PushOnScopeChains(New, S, AddToContext);
4672 if (!AddToContext)
4673 CurContext->addHiddenDecl(New);
4674 }
Mike Stump11289f42009-09-09 15:08:12 +00004675
John McCall48871652010-08-21 09:40:31 +00004676 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004677}
4678
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004679/// Helper method to turn variable array types into constant array
4680/// types in certain situations which would otherwise be errors (for
4681/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004682static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4683 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004684 bool &SizeIsNegative,
4685 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004686 // This method tries to turn a variable array into a constant
4687 // array even when the size isn't an ICE. This is necessary
4688 // for compatibility with code that depends on gcc's buggy
4689 // constant expression folding, like struct {char x[(int)(char*)2];}
4690 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004691 Oversized = 0;
4692
4693 if (T->isDependentType())
4694 return QualType();
4695
John McCall8ccfcb52009-09-24 19:53:00 +00004696 QualifierCollector Qs;
4697 const Type *Ty = Qs.strip(T);
4698
4699 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004700 QualType Pointee = PTy->getPointeeType();
4701 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004702 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4703 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004704 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004705 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004706 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004707 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004708 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4709 QualType Inner = PTy->getInnerType();
4710 QualType FixedType =
4711 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4712 Oversized);
4713 if (FixedType.isNull()) return FixedType;
4714 FixedType = Context.getParenType(FixedType);
4715 return Qs.apply(Context, FixedType);
4716 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004717
4718 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004719 if (!VLATy)
4720 return QualType();
4721 // FIXME: We should probably handle this case
4722 if (VLATy->getElementType()->isVariablyModifiedType())
4723 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004724
Richard Smith42d3af92011-12-07 00:43:50 +00004725 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004726 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004727 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004728 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004729
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004730 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004731 if (Res.isSigned() && Res.isNegative()) {
4732 SizeIsNegative = true;
4733 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004734 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004735
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004736 // Check whether the array is too large to be addressed.
4737 unsigned ActiveSizeBits
4738 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4739 Res);
4740 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4741 Oversized = Res;
4742 return QualType();
4743 }
4744
4745 return Context.getConstantArrayType(VLATy->getElementType(),
4746 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004747}
4748
Abramo Bagnara341ab732012-11-08 14:44:42 +00004749static void
4750FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004751 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4752 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4753 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4754 DstPTL.getPointeeLoc());
4755 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004756 return;
4757 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004758 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4759 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4760 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4761 DstPTL.getInnerLoc());
4762 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4763 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004764 return;
4765 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004766 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4767 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4768 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4769 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004770 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004771 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4772 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4773 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004774}
4775
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004776/// Helper method to turn variable array types into constant array
4777/// types in certain situations which would otherwise be errors (for
4778/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004779static TypeSourceInfo*
4780TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4781 ASTContext &Context,
4782 bool &SizeIsNegative,
4783 llvm::APSInt &Oversized) {
4784 QualType FixedTy
4785 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4786 SizeIsNegative, Oversized);
4787 if (FixedTy.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00004788 return nullptr;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004789 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4790 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4791 FixedTInfo->getTypeLoc());
4792 return FixedTInfo;
4793}
4794
Richard Smith78165b52013-01-10 23:43:47 +00004795/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004796/// that it can be found later for redeclarations. We include any extern "C"
4797/// declaration that is not visible in the translation unit here, not just
4798/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004799void
Richard Smith39b79682013-06-18 20:15:12 +00004800Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004801 if (!getLangOpts().CPlusPlus &&
4802 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4803 // Don't need to track declarations in the TU in C.
4804 return;
4805
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004806 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004807 // FIXME: There can be multiple such declarations if they are functions marked
4808 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004809 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004810}
4811
Richard Smith39b79682013-06-18 20:15:12 +00004812NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004813 if (ExternalSource) {
4814 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004815 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004816 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004817 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004818 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4819 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004820 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4821 if (Pos == LocallyScopedExternCDecls.end())
4822 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004823 }
4824 }
Richard Smith39b79682013-06-18 20:15:12 +00004825
4826 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00004827 return D ? D->getMostRecentDecl() : nullptr;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004828}
4829
Eli Friedman574c7452009-04-07 19:37:57 +00004830/// \brief Diagnose function specifiers on a declaration of an identifier that
4831/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004832void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004833 // FIXME: We should probably indicate the identifier in question to avoid
4834 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004835 if (DS.isInlineSpecified())
4836 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004837 diag::err_inline_non_function);
4838
Richard Smithb1402ae2013-03-18 22:52:47 +00004839 if (DS.isVirtualSpecified())
4840 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004841 diag::err_virtual_non_function);
4842
Richard Smithb1402ae2013-03-18 22:52:47 +00004843 if (DS.isExplicitSpecified())
4844 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004845 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004846
Richard Smithb1402ae2013-03-18 22:52:47 +00004847 if (DS.isNoreturnSpecified())
4848 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004849 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004850}
4851
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004852NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004853Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004854 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004855 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4856 if (D.getCXXScopeSpec().isSet()) {
4857 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4858 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004859 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004860 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004861 DC = CurContext;
4862 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004863 }
4864
Richard Smithb1402ae2013-03-18 22:52:47 +00004865 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004866
Richard Smitha77a0a62011-08-15 21:04:07 +00004867 if (D.getDeclSpec().isConstexprSpecified())
4868 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4869 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004870
Douglas Gregord8f446f2010-07-13 06:37:01 +00004871 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4872 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4873 << D.getName().getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004874 return nullptr;
Douglas Gregord8f446f2010-07-13 06:37:01 +00004875 }
4876
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004877 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Craig Topperc3ec1492014-05-26 06:22:03 +00004878 if (!NewTD) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004879
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004880 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004881 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004882
Richard Smith3f1b5d02011-05-05 21:57:07 +00004883 CheckTypedefForVariablyModifiedType(S, NewTD);
4884
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004885 bool Redeclaration = D.isRedeclaration();
4886 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4887 D.setRedeclaration(Redeclaration);
4888 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004889}
4890
Richard Smith3f1b5d02011-05-05 21:57:07 +00004891void
4892Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004893 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4894 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004895 // Note that variably modified types must be fixed before merging the decl so
4896 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004897 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4898 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004899 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004900 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004901
Craig Topperc3ec1492014-05-26 06:22:03 +00004902 if (S->getFnParent() == nullptr) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004903 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004904 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004905 TypeSourceInfo *FixedTInfo =
4906 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4907 SizeIsNegative,
4908 Oversized);
4909 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004910 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004911 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004912 } else {
4913 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004914 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004915 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004916 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004917 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004918 Diag(NewTD->getLocation(), diag::err_array_too_large)
4919 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004920 else
Richard Smithdda56e42011-04-15 14:24:37 +00004921 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004922 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004923 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004924 }
4925 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004926}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004927
Richard Smith3f1b5d02011-05-05 21:57:07 +00004928
4929/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4930/// declares a typedef-name, either using the 'typedef' type specifier or via
4931/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4932NamedDecl*
4933Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4934 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004935 // Merge the decl with the existing one if appropriate. If the decl is
4936 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004937 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4938 /*AllowInlineNamespace*/false);
Richard Smithca40f9b2014-08-10 02:20:15 +00004939 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004940 if (!Previous.empty()) {
4941 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004942 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004943 }
4944
Douglas Gregor27821ce2009-07-07 16:35:42 +00004945 // If this is the C FILE type, notify the AST context.
4946 if (IdentifierInfo *II = NewTD->getIdentifier())
4947 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004948 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004949 if (II->isStr("FILE"))
4950 Context.setFILEDecl(NewTD);
4951 else if (II->isStr("jmp_buf"))
4952 Context.setjmp_bufDecl(NewTD);
4953 else if (II->isStr("sigjmp_buf"))
4954 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004955 else if (II->isStr("ucontext_t"))
4956 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004957 }
4958
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004959 return NewTD;
4960}
4961
Douglas Gregor5d68a202009-02-24 19:23:27 +00004962/// \brief Determines whether the given declaration is an out-of-scope
4963/// previous declaration.
4964///
4965/// This routine should be invoked when name lookup has found a
4966/// previous declaration (PrevDecl) that is not in the scope where a
4967/// new declaration by the same name is being introduced. If the new
4968/// declaration occurs in a local scope, previous declarations with
4969/// linkage may still be considered previous declarations (C99
4970/// 6.2.2p4-5, C++ [basic.link]p6).
4971///
4972/// \param PrevDecl the previous declaration found by name
4973/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004974///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004975/// \param DC the context in which the new declaration is being
4976/// declared.
4977///
4978/// \returns true if PrevDecl is an out-of-scope previous declaration
4979/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004980static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004981isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4982 ASTContext &Context) {
4983 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004984 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004985
Douglas Gregoreddf4332009-02-24 20:03:32 +00004986 if (!PrevDecl->hasLinkage())
4987 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004988
David Blaikiebbafb8a2012-03-11 07:00:24 +00004989 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004990 // C++ [basic.link]p6:
4991 // If there is a visible declaration of an entity with linkage
4992 // having the same name and type, ignoring entities declared
4993 // outside the innermost enclosing namespace scope, the block
4994 // scope declaration declares that same entity and receives the
4995 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004996 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004997 if (!OuterContext->isFunctionOrMethod())
4998 // This rule only applies to block-scope declarations.
4999 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00005000
5001 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5002 if (PrevOuterContext->isRecord())
5003 // We found a member function: ignore it.
5004 return false;
5005
5006 // Find the innermost enclosing namespace for the new and
5007 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00005008 OuterContext = OuterContext->getEnclosingNamespaceContext();
5009 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00005010
Douglas Gregorfcee9462010-08-27 22:55:10 +00005011 // The previous declaration is in a different namespace, so it
5012 // isn't the same function.
5013 if (!OuterContext->Equals(PrevOuterContext))
5014 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00005015 }
5016
Douglas Gregor5d68a202009-02-24 19:23:27 +00005017 return true;
5018}
5019
John McCall3e11ebe2010-03-15 10:12:16 +00005020static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5021 CXXScopeSpec &SS = D.getCXXScopeSpec();
5022 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00005023 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00005024}
5025
John McCall31168b02011-06-15 23:02:42 +00005026bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5027 QualType type = decl->getType();
5028 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5029 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5030 // Various kinds of declaration aren't allowed to be __autoreleasing.
5031 unsigned kind = -1U;
5032 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5033 if (var->hasAttr<BlocksAttr>())
5034 kind = 0; // __block
5035 else if (!var->hasLocalStorage())
5036 kind = 1; // global
5037 } else if (isa<ObjCIvarDecl>(decl)) {
5038 kind = 3; // ivar
5039 } else if (isa<FieldDecl>(decl)) {
5040 kind = 2; // field
5041 }
5042
5043 if (kind != -1U) {
5044 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5045 << kind;
5046 }
5047 } else if (lifetime == Qualifiers::OCL_None) {
5048 // Try to infer lifetime.
5049 if (!type->isObjCLifetimeType())
5050 return false;
5051
5052 lifetime = type->getObjCARCImplicitLifetime();
5053 type = Context.getLifetimeQualifiedType(type, lifetime);
5054 decl->setType(type);
5055 }
5056
5057 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5058 // Thread-local variables cannot have lifetime.
5059 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00005060 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00005061 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00005062 << var->getType();
5063 return true;
5064 }
5065 }
5066
5067 return false;
5068}
5069
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005070static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00005071 // Ensure that an auto decl is deduced otherwise the checks below might cache
5072 // the wrong linkage.
5073 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5074
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005075 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00005076 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00005077 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00005078 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5079 ND.dropAttr<WeakAttr>();
5080 }
5081 }
5082 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00005083 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00005084 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5085 ND.dropAttr<WeakRefAttr>();
5086 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005087 }
Reid Klecknerb144d362013-05-20 14:02:37 +00005088
5089 // 'selectany' only applies to externally visible varable declarations.
5090 // It does not apply to functions.
5091 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5092 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5093 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5094 ND.dropAttr<SelectAnyAttr>();
5095 }
5096 }
Nico Rieck8ca0bfc2014-03-31 14:56:58 +00005097
5098 // dll attributes require external linkage.
5099 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
5100 if (!ND.isExternallyVisible()) {
5101 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5102 << &ND << Attr;
5103 ND.setInvalidDecl();
5104 }
5105 }
5106 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
5107 if (!ND.isExternallyVisible()) {
5108 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5109 << &ND << Attr;
5110 ND.setInvalidDecl();
5111 }
5112 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005113}
5114
Nico Rieck82f0b062014-03-31 14:56:15 +00005115static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5116 NamedDecl *NewDecl,
5117 bool IsSpecialization) {
5118 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5119 OldDecl = OldTD->getTemplatedDecl();
5120 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5121 NewDecl = NewTD->getTemplatedDecl();
5122
5123 if (!OldDecl || !NewDecl)
Hans Wennborgdd96db22014-08-27 21:27:40 +00005124 return;
Nico Rieck82f0b062014-03-31 14:56:15 +00005125
5126 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5127 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5128 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5129 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5130
5131 // dllimport and dllexport are inheritable attributes so we have to exclude
5132 // inherited attribute instances.
5133 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5134 (NewExportAttr && !NewExportAttr->isInherited());
5135
5136 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5137 // the only exception being explicit specializations.
5138 // Implicitly generated declarations are also excluded for now because there
5139 // is no other way to switch these to use dllimport or dllexport.
5140 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
Hans Wennborgdd96db22014-08-27 21:27:40 +00005141
Nico Rieck82f0b062014-03-31 14:56:15 +00005142 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
Hans Wennborgdd96db22014-08-27 21:27:40 +00005143 // If the declaration hasn't been used yet, allow with a warning for
5144 // free functions and global variables.
5145 bool JustWarn = false;
5146 if (!OldDecl->isUsed() && OldDecl->getDeclContext()->isFileContext()) {
5147 auto *VD = dyn_cast<VarDecl>(OldDecl);
5148 if (VD && !VD->getDescribedVarTemplate())
5149 JustWarn = true;
5150 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5151 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5152 JustWarn = true;
5153 }
5154
5155 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5156 : diag::err_attribute_dll_redeclaration;
5157 S.Diag(NewDecl->getLocation(), DiagID)
5158 << NewDecl
5159 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
Nico Rieck82f0b062014-03-31 14:56:15 +00005160 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
Hans Wennborgdd96db22014-08-27 21:27:40 +00005161 if (!JustWarn) {
5162 NewDecl->setInvalidDecl();
5163 return;
5164 }
Nico Rieck82f0b062014-03-31 14:56:15 +00005165 }
5166
5167 // A redeclaration is not allowed to drop a dllimport attribute, the only
Hans Wennborg7c4851e2014-08-04 20:54:39 +00005168 // exceptions being inline function definitions, local extern declarations,
5169 // and qualified friend declarations.
Nico Rieck82f0b062014-03-31 14:56:15 +00005170 // NB: MSVC converts such a declaration to dllexport.
Hans Wennborg7c4851e2014-08-04 20:54:39 +00005171 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
Nico Rieck078d2f82014-05-29 16:50:20 +00005172 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5173 // Ignore static data because out-of-line definitions are diagnosed
5174 // separately.
5175 IsStaticDataMember = VD->isStaticDataMember();
Hans Wennborg7c4851e2014-08-04 20:54:39 +00005176 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
Nico Rieck078d2f82014-05-29 16:50:20 +00005177 IsInline = FD->isInlined();
Hans Wennborg7c4851e2014-08-04 20:54:39 +00005178 IsQualifiedFriend = FD->getQualifier() &&
5179 FD->getFriendObjectKind() == Decl::FOK_Declared;
5180 }
Hans Wennborgf436b282014-05-22 15:46:15 +00005181
Hans Wennborgf51dc3b2014-07-31 19:29:39 +00005182 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
Hans Wennborg7c4851e2014-08-04 20:54:39 +00005183 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
Nico Rieck82f0b062014-03-31 14:56:15 +00005184 S.Diag(NewDecl->getLocation(),
5185 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5186 << NewDecl << OldImportAttr;
5187 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5188 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5189 OldDecl->dropAttr<DLLImportAttr>();
5190 NewDecl->dropAttr<DLLImportAttr>();
5191 }
5192}
5193
John McCallc87d9722013-04-02 02:48:58 +00005194/// Given that we are within the definition of the given function,
5195/// will that definition behave like C99's 'inline', where the
5196/// definition is discarded except for optimization purposes?
5197static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5198 // Try to avoid calling GetGVALinkageForFunction.
5199
5200 // All cases of this require the 'inline' keyword.
5201 if (!FD->isInlined()) return false;
5202
5203 // This is only possible in C++ with the gnu_inline attribute.
5204 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5205 return false;
5206
5207 // Okay, go ahead and call the relatively-more-expensive function.
5208
5209#ifndef NDEBUG
5210 // AST quite reasonably asserts that it's working on a function
5211 // definition. We don't really have a way to tell it that we're
5212 // currently defining the function, so just lie to it in +Asserts
5213 // builds. This is an awful hack.
5214 FD->setLazyBody(1);
5215#endif
5216
David Majnemer27d69db2014-04-28 22:17:59 +00005217 bool isC99Inline =
5218 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
John McCallc87d9722013-04-02 02:48:58 +00005219
5220#ifndef NDEBUG
5221 FD->setLazyBody(0);
5222#endif
5223
5224 return isC99Inline;
5225}
5226
Richard Smithac974a32013-06-30 09:48:50 +00005227/// Determine whether a variable is extern "C" prior to attaching
5228/// an initializer. We can't just call isExternC() here, because that
5229/// will also compute and cache whether the declaration is externally
5230/// visible, which might change when we attach the initializer.
5231///
5232/// This can only be used if the declaration is known to not be a
5233/// redeclaration of an internal linkage declaration.
5234///
5235/// For instance:
5236///
5237/// auto x = []{};
5238///
5239/// Attaching the initializer here makes this declaration not externally
5240/// visible, because its type has internal linkage.
5241///
5242/// FIXME: This is a hack.
5243template<typename T>
5244static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5245 if (S.getLangOpts().CPlusPlus) {
5246 // In C++, the overloadable attribute negates the effects of extern "C".
5247 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5248 return false;
5249 }
5250 return D->isExternC();
5251}
5252
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005253static bool shouldConsiderLinkage(const VarDecl *VD) {
5254 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5255 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005256 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005257 if (DC->isFileContext())
5258 return true;
5259 if (DC->isRecord())
5260 return false;
5261 llvm_unreachable("Unexpected context");
5262}
5263
5264static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5265 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5266 if (DC->isFileContext() || DC->isFunctionOrMethod())
5267 return true;
5268 if (DC->isRecord())
5269 return false;
5270 llvm_unreachable("Unexpected context");
5271}
5272
Nico Riecke84f8db2014-03-23 21:24:01 +00005273static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5274 AttributeList::Kind Kind) {
5275 for (const AttributeList *L = AttrList; L; L = L->getNext())
5276 if (L->getKind() == Kind)
5277 return true;
5278 return false;
5279}
5280
5281static bool hasParsedAttr(Scope *S, const Declarator &PD,
5282 AttributeList::Kind Kind) {
5283 // Check decl attributes on the DeclSpec.
5284 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5285 return true;
5286
5287 // Walk the declarator structure, checking decl attributes that were in a type
5288 // position to the decl itself.
5289 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5290 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5291 return true;
5292 }
5293
5294 // Finally, check attributes on the decl itself.
5295 return hasParsedAttr(S, PD.getAttributes(), Kind);
5296}
5297
Richard Smith541b38b2013-09-20 01:15:31 +00005298/// Adjust the \c DeclContext for a function or variable that might be a
5299/// function-local external declaration.
5300bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5301 if (!DC->isFunctionOrMethod())
5302 return false;
5303
5304 // If this is a local extern function or variable declared within a function
5305 // template, don't add it into the enclosing namespace scope until it is
5306 // instantiated; it might have a dependent type right now.
5307 if (DC->isDependentContext())
5308 return true;
5309
5310 // C++11 [basic.link]p7:
5311 // When a block scope declaration of an entity with linkage is not found to
5312 // refer to some other declaration, then that entity is a member of the
5313 // innermost enclosing namespace.
5314 //
5315 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5316 // semantically-enclosing namespace, not a lexically-enclosing one.
5317 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5318 DC = DC->getParent();
5319 return true;
5320}
5321
Larisse Voufo39a1e502013-08-06 01:03:05 +00005322NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00005323Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005324 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005325 MultiTemplateParamsArg TemplateParamLists,
5326 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005327 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005328 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005329
Douglas Gregorc4df4072010-04-19 22:54:31 +00005330 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00005331 VarDecl::StorageClass SC =
5332 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00005333
Nico Riecke84f8db2014-03-23 21:24:01 +00005334 // dllimport globals without explicit storage class are treated as extern. We
5335 // have to change the storage class this early to get the right DeclContext.
5336 if (SC == SC_None && !DC->isRecord() &&
Nico Rieck755a36f2014-05-25 10:34:16 +00005337 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5338 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
Nico Riecke84f8db2014-03-23 21:24:01 +00005339 SC = SC_Extern;
5340
Richard Smith541b38b2013-09-20 01:15:31 +00005341 DeclContext *OriginalDC = DC;
5342 bool IsLocalExternDecl = SC == SC_Extern &&
5343 adjustContextForLocalExternDecl(DC);
5344
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005345 if (getLangOpts().OpenCL) {
5346 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5347 QualType NR = R;
5348 while (NR->isPointerType()) {
5349 if (NR->isFunctionPointerType()) {
5350 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5351 D.setInvalidType();
5352 break;
5353 }
5354 NR = NR->getPointeeType();
5355 }
5356
5357 if (!getOpenCLOptions().cl_khr_fp16) {
5358 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5359 // half array type (unless the cl_khr_fp16 extension is enabled).
5360 if (Context.getBaseElementType(R)->isHalfType()) {
5361 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5362 D.setInvalidType();
5363 }
Joey Goulydd7f4562013-01-23 11:56:20 +00005364 }
5365 }
5366
Douglas Gregorc4df4072010-04-19 22:54:31 +00005367 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005368 // mutable can only appear on non-static class members, so it's always
5369 // an error here
5370 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005371 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005372 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005373 }
John McCallc87d9722013-04-02 02:48:58 +00005374
Richard Smithf2c9afc2013-06-17 01:34:01 +00005375 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5376 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5377 D.getDeclSpec().getStorageClassSpecLoc())) {
5378 // In C++11, the 'register' storage class specifier is deprecated.
5379 // Suppress the warning in system macros, it's used in macros in some
5380 // popular C system headers, such as in glibc's htonl() macro.
5381 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5382 diag::warn_deprecated_register)
5383 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5384 }
5385
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005386 IdentifierInfo *II = Name.getAsIdentifierInfo();
5387 if (!II) {
5388 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005389 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00005390 return nullptr;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005391 }
5392
Richard Smithb1402ae2013-03-18 22:52:47 +00005393 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005394
Craig Topperc3ec1492014-05-26 06:22:03 +00005395 if (!DC->isRecord() && S->getFnParent() == nullptr) {
Douglas Gregor212cab32009-03-11 20:22:50 +00005396 // C99 6.9p2: The storage-class specifiers auto and register shall not
5397 // appear in the declaration specifiers in an external declaration.
Renato Golin230c5eb2014-05-19 18:15:42 +00005398 // Global Register+Asm is a GNU extension we support.
5399 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5400 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005401 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005402 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005403 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005404
David Blaikiebbafb8a2012-03-11 07:00:24 +00005405 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005406 // Set up the special work-group-local storage class for variables in the
5407 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005408 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005409 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005410 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005411
Guy Benyei61054192013-02-07 10:55:47 +00005412 // OpenCL v1.2 s6.9.b p4:
5413 // The sampler type cannot be used with the __local and __global address
5414 // space qualifiers.
5415 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5416 R.getAddressSpace() == LangAS::opencl_global)) {
5417 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5418 }
5419
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005420 // OpenCL 1.2 spec, p6.9 r:
5421 // The event type cannot be used to declare a program scope variable.
5422 // The event type cannot be used with the __local, __constant and __global
5423 // address space qualifiers.
5424 if (R->isEventT()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005425 if (S->getParent() == nullptr) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005426 Diag(D.getLocStart(), diag::err_event_t_global_var);
5427 D.setInvalidType();
5428 }
5429
5430 if (R.getAddressSpace()) {
5431 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5432 D.setInvalidType();
5433 }
5434 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005435 }
5436
Larisse Voufo39a1e502013-08-06 01:03:05 +00005437 bool IsExplicitSpecialization = false;
5438 bool IsVariableTemplateSpecialization = false;
5439 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005440 bool IsVariableTemplate = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00005441 VarDecl *NewVD = nullptr;
5442 VarTemplateDecl *NewTemplate = nullptr;
5443 TemplateParameterList *TemplateParams = nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005444 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005445 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005446 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005447 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005448
5449 if (D.isInvalidType())
5450 NewVD->setInvalidDecl();
5451 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005452 bool Invalid = false;
5453
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005454 if (DC->isRecord() && !CurContext->isRecord()) {
5455 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005456 switch (SC) {
5457 case SC_None:
5458 break;
5459 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005460 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5461 diag::err_static_out_of_line)
5462 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005463 break;
5464 case SC_Auto:
5465 case SC_Register:
5466 case SC_Extern:
5467 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5468 // to names of variables declared in a block or to function parameters.
5469 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5470 // of class members
5471
5472 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5473 diag::err_storage_class_for_static_member)
5474 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5475 break;
5476 case SC_PrivateExtern:
5477 llvm_unreachable("C storage class in c++!");
5478 case SC_OpenCLWorkGroupLocal:
5479 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005480 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005481 }
5482
Richard Smith42973752012-02-16 20:41:22 +00005483 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005484 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5485 if (RD->isLocalClass())
5486 Diag(D.getIdentifierLoc(),
5487 diag::err_static_data_member_not_allowed_in_local_class)
5488 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005489
Richard Smith42973752012-02-16 20:41:22 +00005490 // C++98 [class.union]p1: If a union contains a static data member,
5491 // the program is ill-formed. C++11 drops this restriction.
5492 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005493 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005494 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005495 ? diag::warn_cxx98_compat_static_data_member_in_union
5496 : diag::ext_static_data_member_in_union) << Name;
5497 // We conservatively disallow static data members in anonymous structs.
5498 else if (!RD->getDeclName())
5499 Diag(D.getIdentifierLoc(),
5500 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005501 << Name << RD->isUnion();
5502 }
5503 }
5504
5505 // Match up the template parameter lists with the scope specifier, then
5506 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005507 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5508 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00005509 D.getCXXScopeSpec(),
5510 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5511 ? D.getName().TemplateId
Craig Topperc3ec1492014-05-26 06:22:03 +00005512 : nullptr,
Richard Smith4b55a9c2014-04-17 03:29:33 +00005513 TemplateParamLists,
Richard Smithbeef3452014-01-16 23:39:20 +00005514 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005515
Richard Smithbeef3452014-01-16 23:39:20 +00005516 if (TemplateParams) {
5517 if (!TemplateParams->size() &&
5518 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5519 // There is an extraneous 'template<>' for this variable. Complain
5520 // about it, but allow the declaration of the variable.
5521 Diag(TemplateParams->getTemplateLoc(),
5522 diag::err_template_variable_noparams)
5523 << II
5524 << SourceRange(TemplateParams->getTemplateLoc(),
5525 TemplateParams->getRAngleLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +00005526 TemplateParams = nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00005527 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005528 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5529 // This is an explicit specialization or a partial specialization.
5530 // FIXME: Check that we can declare a specialization here.
5531 IsVariableTemplateSpecialization = true;
5532 IsPartialSpecialization = TemplateParams->size() > 0;
5533 } else { // if (TemplateParams->size() > 0)
5534 // This is a template declaration.
5535 IsVariableTemplate = true;
5536
5537 // Check that we can declare a template here.
5538 if (CheckTemplateDeclScope(S, TemplateParams))
Craig Topperc3ec1492014-05-26 06:22:03 +00005539 return nullptr;
Richard Smith0d963d62014-04-17 02:56:49 +00005540
5541 // Only C++1y supports variable templates (N3651).
5542 Diag(D.getIdentifierLoc(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005543 getLangOpts().CPlusPlus14
Richard Smith0d963d62014-04-17 02:56:49 +00005544 ? diag::warn_cxx11_compat_variable_template
5545 : diag::ext_variable_template);
Richard Smithbeef3452014-01-16 23:39:20 +00005546 }
5547 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00005548 } else {
5549 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5550 "should have a 'template<>' for this decl");
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005551 }
Mike Stump11289f42009-09-09 15:08:12 +00005552
Larisse Voufo39a1e502013-08-06 01:03:05 +00005553 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005554 SourceLocation TemplateKWLoc =
5555 TemplateParamLists.size() > 0
5556 ? TemplateParamLists[0]->getTemplateLoc()
5557 : SourceLocation();
5558 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005559 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005560 IsPartialSpecialization);
5561 if (Res.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00005562 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005563 NewVD = cast<VarDecl>(Res.get());
5564 AddToScope = false;
5565 } else
5566 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5567 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005568
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005569 // If this is supposed to be a variable template, create it as such.
5570 if (IsVariableTemplate) {
5571 NewTemplate =
5572 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005573 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005574 NewVD->setDescribedVarTemplate(NewTemplate);
5575 }
5576
Richard Smithb2bc2e62011-02-21 20:05:19 +00005577 // If this decl has an auto type in need of deduction, make a note of the
5578 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005579 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005580 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005581
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005582 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005583 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005584 if (NewTemplate)
5585 NewTemplate->setInvalidDecl();
5586 }
Mike Stump11289f42009-09-09 15:08:12 +00005587
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005588 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005589
Richard Smith72db5632014-01-25 21:32:06 +00005590 // If we have any template parameter lists that don't directly belong to
5591 // the variable (matching the scope specifier), store them.
5592 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5593 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005594 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005595 Context, TemplateParamLists.size() - VDTemplateParamLists,
5596 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005597
Richard Smith6331c402012-02-13 22:16:19 +00005598 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005599 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005600 }
5601
Douglas Gregor41866812011-09-12 18:37:38 +00005602 // Set the lexical context. If the declarator has a C++ scope specifier, the
5603 // lexical context will be different from the semantic context.
5604 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005605 if (NewTemplate)
5606 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005607
Richard Smith541b38b2013-09-20 01:15:31 +00005608 if (IsLocalExternDecl)
5609 NewVD->setLocalExternDecl();
5610
Richard Smithb4a9e862013-04-12 22:46:28 +00005611 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005612 if (NewVD->hasLocalStorage()) {
5613 // C++11 [dcl.stc]p4:
5614 // When thread_local is applied to a variable of block scope the
5615 // storage-class-specifier static is implied if it does not appear
5616 // explicitly.
5617 // Core issue: 'static' is not implied if the variable is declared
5618 // 'extern'.
5619 if (SCSpec == DeclSpec::SCS_unspecified &&
5620 TSCS == DeclSpec::TSCS_thread_local &&
5621 DC->isFunctionOrMethod())
5622 NewVD->setTSCSpec(TSCS);
5623 else
5624 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5625 diag::err_thread_non_global)
5626 << DeclSpec::getSpecifierName(TSCS);
5627 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005628 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5629 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005630 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005631 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005632 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005633
John McCallc87d9722013-04-02 02:48:58 +00005634 // C99 6.7.4p3
5635 // An inline definition of a function with external linkage shall
5636 // not contain a definition of a modifiable object with static or
5637 // thread storage duration...
5638 // We only apply this when the function is required to be defined
5639 // elsewhere, i.e. when the function is not 'extern inline'. Note
5640 // that a local variable with thread storage duration still has to
5641 // be marked 'static'. Also note that it's possible to get these
5642 // semantics in C++ using __attribute__((gnu_inline)).
Craig Topperc3ec1492014-05-26 06:22:03 +00005643 if (SC == SC_Static && S->getFnParent() != nullptr &&
John McCallc87d9722013-04-02 02:48:58 +00005644 !NewVD->getType().isConstQualified()) {
5645 FunctionDecl *CurFD = getCurFunctionDecl();
5646 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5647 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5648 diag::warn_static_local_in_extern_inline);
5649 MaybeSuggestAddingStaticToDecl(CurFD);
5650 }
5651 }
5652
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005653 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005654 if (IsVariableTemplateSpecialization)
5655 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5656 << (IsPartialSpecialization ? 1 : 0)
5657 << FixItHint::CreateRemoval(
5658 D.getDeclSpec().getModulePrivateSpecLoc());
5659 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005660 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5661 << 2
5662 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005663 else if (NewVD->hasLocalStorage())
5664 Diag(NewVD->getLocation(), diag::err_module_private_local)
5665 << 0 << NewVD->getDeclName()
5666 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5667 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005668 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005669 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005670 if (NewTemplate)
5671 NewTemplate->setModulePrivate();
5672 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005673 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005674
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005675 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005676 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005677
Peter Collingbournec6b08572012-08-28 20:37:50 +00005678 if (getLangOpts().CUDA) {
5679 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5680 // storage [duration]."
Craig Topperc3ec1492014-05-26 06:22:03 +00005681 if (SC == SC_None && S->getFnParent() != nullptr &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005682 (NewVD->hasAttr<CUDASharedAttr>() ||
5683 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005684 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005685 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005686 }
5687
Nico Riecke84f8db2014-03-23 21:24:01 +00005688 // Ensure that dllimport globals without explicit storage class are treated as
5689 // extern. The storage class is set above using parsed attributes. Now we can
5690 // check the VarDecl itself.
5691 assert(!NewVD->hasAttr<DLLImportAttr>() ||
5692 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5693 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5694
John McCall31168b02011-06-15 23:02:42 +00005695 // In auto-retain/release, infer strong retension for variables of
5696 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005697 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005698 NewVD->setInvalidDecl();
5699
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005700 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005701 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005702 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005703 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005704 StringRef Label = SE->getString();
Craig Topperc3ec1492014-05-26 06:22:03 +00005705 if (S->getFnParent() != nullptr) {
Abramo Bagnara13392232011-01-11 15:16:52 +00005706 switch (SC) {
5707 case SC_None:
5708 case SC_Auto:
5709 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5710 break;
5711 case SC_Register:
Renato Golin230c5eb2014-05-19 18:15:42 +00005712 // Local Named register
Douglas Gregore8bbc122011-09-02 00:18:52 +00005713 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005714 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5715 break;
5716 case SC_Static:
5717 case SC_Extern:
5718 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005719 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005720 break;
5721 }
Renato Golin230c5eb2014-05-19 18:15:42 +00005722 } else if (SC == SC_Register) {
5723 // Global Named register
5724 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5725 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
Renato Golin2e31e4e2014-06-05 16:45:22 +00005726 if (!R->isIntegralType(Context) && !R->isPointerType()) {
5727 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5728 NewVD->setInvalidDecl(true);
5729 }
Abramo Bagnara13392232011-01-11 15:16:52 +00005730 }
5731
5732 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005733 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005734 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5735 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5736 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5737 if (I != ExtnameUndeclaredIdentifiers.end()) {
5738 NewVD->addAttr(I->second);
5739 ExtnameUndeclaredIdentifiers.erase(I);
5740 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005741 }
5742
John McCalla2a3f7d2010-03-16 21:48:18 +00005743 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005744 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005745 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005746
John McCall1f82f242009-11-18 22:49:29 +00005747 // Don't consider existing declarations that are in a different
5748 // scope and are out-of-semantic-context declarations (if the new
5749 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005750 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5751 D.getCXXScopeSpec().isNotEmpty() ||
5752 IsExplicitSpecialization ||
5753 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005754
Richard Smith1c34fb72013-08-13 18:18:50 +00005755 // Check whether the previous declaration is in the same block scope. This
5756 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5757 if (getLangOpts().CPlusPlus &&
5758 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5759 NewVD->setPreviousDeclInSameBlockScope(
5760 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005761 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005762
David Blaikiebbafb8a2012-03-11 07:00:24 +00005763 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005764 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5765 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005766 // If this is an explicit specialization of a static data member, check it.
5767 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5768 CheckMemberSpecialization(NewVD, Previous))
5769 NewVD->setInvalidDecl();
5770
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005771 // Merge the decl with the existing one if appropriate.
5772 if (!Previous.empty()) {
5773 if (Previous.isSingleResult() &&
5774 isa<FieldDecl>(Previous.getFoundDecl()) &&
5775 D.getCXXScopeSpec().isSet()) {
5776 // The user tried to define a non-static data member
5777 // out-of-line (C++ [dcl.meaning]p1).
5778 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5779 << D.getCXXScopeSpec().getRange();
5780 Previous.clear();
5781 NewVD->setInvalidDecl();
5782 }
5783 } else if (D.getCXXScopeSpec().isSet()) {
5784 // No previous declaration in the qualifying scope.
5785 Diag(D.getIdentifierLoc(), diag::err_no_member)
5786 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005787 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005788 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005789 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005790
Richard Smithbeef3452014-01-16 23:39:20 +00005791 if (!IsVariableTemplateSpecialization)
5792 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005793
Richard Smithbeef3452014-01-16 23:39:20 +00005794 if (NewTemplate) {
5795 VarTemplateDecl *PrevVarTemplate =
5796 NewVD->getPreviousDecl()
5797 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
Craig Topperc3ec1492014-05-26 06:22:03 +00005798 : nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00005799
5800 // Check the template parameter list of this declaration, possibly
5801 // merging in the template parameter list from the previous variable
5802 // template declaration.
5803 if (CheckTemplateParameterList(
5804 TemplateParams,
5805 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
Craig Topperc3ec1492014-05-26 06:22:03 +00005806 : nullptr,
Richard Smithbeef3452014-01-16 23:39:20 +00005807 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5808 DC->isDependentContext())
5809 ? TPC_ClassTemplateMember
5810 : TPC_VarTemplate))
5811 NewVD->setInvalidDecl();
5812
5813 // If we are providing an explicit specialization of a static variable
5814 // template, make a note of that.
5815 if (PrevVarTemplate &&
5816 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5817 PrevVarTemplate->setMemberSpecialization();
5818 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005819 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005820
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005821 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005822
Richard Smithac974a32013-06-30 09:48:50 +00005823 // If this is the first declaration of an extern C variable, update
5824 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005825 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005826 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005827 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005828
Reid Klecknerd8110b62013-09-10 20:14:30 +00005829 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005830 Decl *ManglingContextDecl;
5831 if (MangleNumberingContext *MCtx =
5832 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5833 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005834 Context.setManglingNumber(
5835 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005836 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005837 }
5838 }
5839
Nico Rieck82f0b062014-03-31 14:56:15 +00005840 if (D.isRedeclaration() && !Previous.empty()) {
5841 checkDLLAttributeRedeclaration(
5842 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5843 IsExplicitSpecialization);
5844 }
5845
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005846 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005847 if (NewVD->isInvalidDecl())
5848 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005849 ActOnDocumentableDecl(NewTemplate);
5850 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005851 }
5852
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005853 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005854}
5855
John McCalldf8b37c2010-03-22 09:20:08 +00005856/// \brief Diagnose variable or built-in function shadowing. Implements
5857/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005858///
John McCalldf8b37c2010-03-22 09:20:08 +00005859/// This method is called whenever a VarDecl is added to a "useful"
5860/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005861///
John McCall2d8c7602010-03-20 04:12:52 +00005862/// \param S the scope in which the shadowing name is being declared
5863/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005864///
John McCalldf8b37c2010-03-22 09:20:08 +00005865void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005866 // Return if warning is ignored.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005867 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
John McCalla2a3f7d2010-03-16 21:48:18 +00005868 return;
5869
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005870 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005871 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005872 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005873
5874 DeclContext *NewDC = D->getDeclContext();
5875
John McCall2d8c7602010-03-20 04:12:52 +00005876 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005877 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005878 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005879
John McCalla2a3f7d2010-03-16 21:48:18 +00005880 NamedDecl* ShadowedDecl = R.getFoundDecl();
5881 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5882 return;
5883
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005884 // Fields are not shadowed by variables in C++ static methods.
5885 if (isa<FieldDecl>(ShadowedDecl))
5886 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5887 if (MD->isStatic())
5888 return;
5889
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005890 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5891 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005892 // For shadowing external vars, make sure that we point to the global
5893 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005894 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005895 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005896 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005897 break;
5898 }
5899 }
5900
5901 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5902
John McCall2d8c7602010-03-20 04:12:52 +00005903 // Only warn about certain kinds of shadowing for class members.
5904 if (NewDC && NewDC->isRecord()) {
5905 // In particular, don't warn about shadowing non-class members.
5906 if (!OldDC->isRecord())
5907 return;
5908
5909 // TODO: should we warn about static data members shadowing
5910 // static data members from base classes?
5911
5912 // TODO: don't diagnose for inaccessible shadowed members.
5913 // This is hard to do perfectly because we might friend the
5914 // shadowing context, but that's just a false negative.
5915 }
5916
5917 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005918 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005919 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005920 if (isa<FieldDecl>(ShadowedDecl))
5921 Kind = 3; // field
5922 else
5923 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005924 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005925 Kind = 1; // global
5926 else
5927 Kind = 0; // local
5928
John McCall2d8c7602010-03-20 04:12:52 +00005929 DeclarationName Name = R.getLookupName();
5930
John McCalla2a3f7d2010-03-16 21:48:18 +00005931 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005932 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5933 return;
John McCall2d8c7602010-03-20 04:12:52 +00005934 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005935 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5936}
5937
John McCalldf8b37c2010-03-22 09:20:08 +00005938/// \brief Check -Wshadow without the advantage of a previous lookup.
5939void Sema::CheckShadow(Scope *S, VarDecl *D) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005940 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005941 return;
5942
John McCalldf8b37c2010-03-22 09:20:08 +00005943 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5944 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5945 LookupName(R, S);
5946 CheckShadow(S, D, R);
5947}
5948
Richard Smithac974a32013-06-30 09:48:50 +00005949/// Check for conflict between this global or extern "C" declaration and
5950/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005951template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005952static bool checkGlobalOrExternCConflict(
5953 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5954 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5955 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005956
Richard Smithac974a32013-06-30 09:48:50 +00005957 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5958 // The common case: this global doesn't conflict with any extern "C"
5959 // declaration.
5960 return false;
5961 }
5962
5963 if (Prev) {
5964 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5965 // Both the old and new declarations have C language linkage. This is a
5966 // redeclaration.
5967 Previous.clear();
5968 Previous.addDecl(Prev);
5969 return true;
5970 }
5971
5972 // This is a global, non-extern "C" declaration, and there is a previous
5973 // non-global extern "C" declaration. Diagnose if this is a variable
5974 // declaration.
5975 if (!isa<VarDecl>(ND))
5976 return false;
5977 } else {
5978 // The declaration is extern "C". Check for any declaration in the
5979 // translation unit which might conflict.
5980 if (IsGlobal) {
5981 // We have already performed the lookup into the translation unit.
5982 IsGlobal = false;
5983 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5984 I != E; ++I) {
5985 if (isa<VarDecl>(*I)) {
5986 Prev = *I;
5987 break;
5988 }
5989 }
5990 } else {
5991 DeclContext::lookup_result R =
5992 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5993 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5994 I != E; ++I) {
5995 if (isa<VarDecl>(*I)) {
5996 Prev = *I;
5997 break;
5998 }
5999 // FIXME: If we have any other entity with this name in global scope,
6000 // the declaration is ill-formed, but that is a defect: it breaks the
6001 // 'stat' hack, for instance. Only variables can have mangled name
6002 // clashes with extern "C" declarations, so only they deserve a
6003 // diagnostic.
6004 }
6005 }
6006
6007 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00006008 return false;
6009 }
6010
Richard Smithac974a32013-06-30 09:48:50 +00006011 // Use the first declaration's location to ensure we point at something which
6012 // is lexically inside an extern "C" linkage-spec.
6013 assert(Prev && "should have found a previous declaration to diagnose");
6014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00006015 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00006016 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00006017 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00006018
6019 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6020 << IsGlobal << ND;
6021 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6022 << IsGlobal;
6023 return false;
6024}
6025
6026/// Apply special rules for handling extern "C" declarations. Returns \c true
6027/// if we have found that this is a redeclaration of some prior entity.
6028///
6029/// Per C++ [dcl.link]p6:
6030/// Two declarations [for a function or variable] with C language linkage
6031/// with the same name that appear in different scopes refer to the same
6032/// [entity]. An entity with C language linkage shall not be declared with
6033/// the same name as an entity in global scope.
6034template<typename T>
6035static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6036 LookupResult &Previous) {
6037 if (!S.getLangOpts().CPlusPlus) {
6038 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00006039 // variable declared in function scope. We don't need this in C++, because
6040 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00006041 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6042 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6043 Previous.clear();
6044 Previous.addDecl(Prev);
6045 return true;
6046 }
6047 }
6048 return false;
6049 }
6050
6051 // A declaration in the translation unit can conflict with an extern "C"
6052 // declaration.
6053 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6054 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6055
6056 // An extern "C" declaration can conflict with a declaration in the
6057 // translation unit or can be a redeclaration of an extern "C" declaration
6058 // in another scope.
6059 if (isIncompleteDeclExternC(S,ND))
6060 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6061
6062 // Neither global nor extern "C": nothing to do.
6063 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00006064}
6065
Richard Smith27d807c2013-04-30 13:56:41 +00006066void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006067 // If the decl is already known invalid, don't check it.
6068 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00006069 return;
Mike Stump11289f42009-09-09 15:08:12 +00006070
Abramo Bagnara341ab732012-11-08 14:44:42 +00006071 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6072 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00006073
Richard Smith27d807c2013-04-30 13:56:41 +00006074 // Defer checking an 'auto' type until its initializer is attached.
6075 if (T->isUndeducedType())
6076 return;
6077
Richard Smithdc4ccaa2014-03-27 01:22:48 +00006078 if (NewVD->hasAttrs())
6079 CheckAlignasUnderalignment(NewVD);
6080
John McCall8b07ec22010-05-15 11:32:37 +00006081 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00006082 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6083 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00006084 T = Context.getObjCObjectPointerType(T);
6085 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00006086 }
Mike Stump11289f42009-09-09 15:08:12 +00006087
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006088 // Emit an error if an address space was applied to decl with local storage.
6089 // This includes arrays of objects with address space qualifiers, but not
6090 // automatic variables that point to other address spaces.
6091 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00006092 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00006093 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006094 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00006095 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006096 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00006097
Tanya Lattner713eef42013-04-05 20:14:50 +00006098 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6099 // __constant address space.
6100 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6101 && T.getAddressSpace() != LangAS::opencl_constant
6102 && !T->isSamplerT()){
6103 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6104 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00006105 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00006106 }
6107
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00006108 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6109 // scope.
6110 if ((getLangOpts().OpenCLVersion >= 120)
6111 && NewVD->isStaticLocal()) {
6112 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6113 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00006114 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00006115 }
6116
Mike Stumpca5ae662009-04-14 00:57:29 +00006117 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00006118 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006119 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00006120 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00006121 else {
6122 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00006123 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00006124 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00006125 }
Chris Lattner88fdea82010-10-10 18:16:20 +00006126
Chris Lattner9fecd742009-04-19 05:21:20 +00006127 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00006128 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00006129 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00006130 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00006131
Chris Lattner9fecd742009-04-19 05:21:20 +00006132 if ((isVM && NewVD->hasLinkage()) ||
6133 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00006134 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006135 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00006136 TypeSourceInfo *FixedTInfo =
6137 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6138 SizeIsNegative, Oversized);
Craig Topperc3ec1492014-05-26 06:22:03 +00006139 if (!FixedTInfo && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00006140 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00006141 // FIXME: This won't give the correct result for
6142 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00006143 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00006144
Anders Carlsson6c885802009-02-28 21:56:50 +00006145 if (NewVD->isFileVarDecl())
6146 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006147 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00006148 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00006149 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006150 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00006151 else
6152 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006153 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006154 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00006155 return;
Mike Stump11289f42009-09-09 15:08:12 +00006156 }
6157
Craig Topperc3ec1492014-05-26 06:22:03 +00006158 if (!FixedTInfo) {
Anders Carlsson6c885802009-02-28 21:56:50 +00006159 if (NewVD->isFileVarDecl())
6160 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6161 else
6162 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006163 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00006164 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00006165 }
Mike Stump11289f42009-09-09 15:08:12 +00006166
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006167 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00006168 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00006169 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00006170 }
6171
David Majnemer0ffa3312013-05-29 00:56:45 +00006172 if (T->isVoidType()) {
6173 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6174 // of objects and functions.
6175 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6176 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6177 << T;
6178 NewVD->setInvalidDecl();
6179 return;
6180 }
Richard Smith27d807c2013-04-30 13:56:41 +00006181 }
6182
6183 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6184 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6185 NewVD->setInvalidDecl();
6186 return;
6187 }
6188
6189 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6190 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6191 NewVD->setInvalidDecl();
6192 return;
6193 }
6194
6195 if (NewVD->isConstexpr() && !T->isDependentType() &&
6196 RequireLiteralType(NewVD->getLocation(), T,
6197 diag::err_constexpr_var_non_literal)) {
Richard Smith27d807c2013-04-30 13:56:41 +00006198 NewVD->setInvalidDecl();
6199 return;
6200 }
6201}
6202
6203/// \brief Perform semantic checking on a newly-created variable
6204/// declaration.
6205///
6206/// This routine performs all of the type-checking required for a
6207/// variable declaration once it has been built. It is used both to
6208/// check variables after they have been parsed and their declarators
6209/// have been translated into a declaration, and to check variables
6210/// that have been instantiated from a template.
6211///
6212/// Sets NewVD->isInvalidDecl() if an error was encountered.
6213///
6214/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00006215bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00006216 CheckVariableDeclarationType(NewVD);
6217
6218 // If the decl is already known invalid, don't check it.
6219 if (NewVD->isInvalidDecl())
6220 return false;
6221
John McCallb65e8fe2013-04-01 18:34:28 +00006222 // If we did not find anything by this name, look for a non-visible
6223 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00006224 if (Previous.empty() &&
6225 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00006226 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006227
Douglas Gregor3552dab2013-01-09 00:47:56 +00006228 // Filter out any non-conflicting previous declarations.
6229 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6230
John McCall1f82f242009-11-18 22:49:29 +00006231 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00006232 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006233 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006234 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006235 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006236}
6237
Douglas Gregor36d1b142009-10-06 17:59:45 +00006238/// \brief Data used with FindOverriddenMethod
6239struct FindOverriddenMethodData {
6240 Sema *S;
6241 CXXMethodDecl *Method;
6242};
6243
6244/// \brief Member lookup function that determines whether a given C++
6245/// method overrides a method in a base class, to be used with
6246/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00006247static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00006248 CXXBasePath &Path,
6249 void *UserData) {
6250 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00006251
Douglas Gregor36d1b142009-10-06 17:59:45 +00006252 FindOverriddenMethodData *Data
6253 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00006254
6255 DeclarationName Name = Data->Method->getDeclName();
6256
6257 // FIXME: Do we care about other names here too?
6258 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00006259 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00006260 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6261 CanQualType CT = Data->S->Context.getCanonicalType(T);
6262
Anders Carlsson5a4f7722009-11-27 01:26:58 +00006263 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00006264 }
6265
6266 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006267 !Path.Decls.empty();
6268 Path.Decls = Path.Decls.slice(1)) {
6269 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00006270 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6271 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00006272 return true;
6273 }
6274 }
6275
6276 return false;
6277}
6278
David Blaikie7e414262012-10-17 00:47:58 +00006279namespace {
6280 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6281}
6282/// \brief Report an error regarding overriding, along with any relevant
6283/// overriden methods.
6284///
6285/// \param DiagID the primary error to report.
6286/// \param MD the overriding method.
6287/// \param OEK which overrides to include as notes.
6288static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6289 OverrideErrorKind OEK = OEK_All) {
6290 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6291 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6292 E = MD->end_overridden_methods();
6293 I != E; ++I) {
6294 // This check (& the OEK parameter) could be replaced by a predicate, but
6295 // without lambdas that would be overkill. This is still nicer than writing
6296 // out the diag loop 3 times.
6297 if ((OEK == OEK_All) ||
6298 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6299 (OEK == OEK_Deleted && (*I)->isDeleted()))
6300 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6301 }
6302}
6303
Sebastian Redld5b24532009-11-18 21:51:29 +00006304/// AddOverriddenMethods - See if a method overrides any in the base classes,
6305/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006306bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00006307 // Look for virtual methods in base classes that this method might override.
6308 CXXBasePaths Paths;
6309 FindOverriddenMethodData Data;
6310 Data.Method = MD;
6311 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00006312 bool hasDeletedOverridenMethods = false;
6313 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006314 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00006315 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
Aaron Ballmane6f465e2014-03-14 21:38:48 +00006316 for (auto *I : Paths.found_decls()) {
6317 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00006318 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00006319 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00006320 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00006321 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00006322 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00006323 hasDeletedOverridenMethods |= OldMD->isDeleted();
6324 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006325 AddedAny = true;
6326 }
Sebastian Redld5b24532009-11-18 21:51:29 +00006327 }
6328 }
6329 }
David Blaikie7e414262012-10-17 00:47:58 +00006330
6331 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6332 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6333 }
6334 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6335 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6336 }
6337
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006338 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00006339}
6340
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006341namespace {
6342 // Struct for holding all of the extra arguments needed by
6343 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6344 struct ActOnFDArgs {
6345 Scope *S;
6346 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006347 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006348 bool AddToScope;
6349 };
6350}
6351
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006352namespace {
6353
6354// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006355// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006356class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6357 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006358 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6359 CXXRecordDecl *Parent)
6360 : Context(Context), OriginalFD(TypoFD),
Craig Topperc3ec1492014-05-26 06:22:03 +00006361 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006362
Craig Toppere14c0f82014-03-12 04:55:44 +00006363 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006364 if (candidate.getEditDistance() == 0)
6365 return false;
6366
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006367 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006368 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6369 CDeclEnd = candidate.end();
6370 CDecl != CDeclEnd; ++CDecl) {
6371 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6372
6373 if (FD && !FD->hasBody() &&
6374 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6375 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6376 CXXRecordDecl *Parent = MD->getParent();
6377 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6378 return true;
6379 } else if (!ExpectedParent) {
6380 return true;
6381 }
6382 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006383 }
6384
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006385 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006386 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006387
6388 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006389 ASTContext &Context;
6390 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006391 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006392};
6393
6394}
6395
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006396/// \brief Generate diagnostics for an invalid function redeclaration.
6397///
6398/// This routine handles generating the diagnostic messages for an invalid
6399/// function redeclaration, including finding possible similar declarations
6400/// or performing typo correction if there are no previous declarations with
6401/// the same name.
6402///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006403/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006404/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006405static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006406 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006407 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006408 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006409 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006410 SmallVector<unsigned, 1> MismatchedParams;
6411 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006412 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006413 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006414 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6415 : diag::err_member_decl_does_not_match;
6416 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6417 IsLocalFriend ? Sema::LookupLocalFriendName
6418 : Sema::LookupOrdinaryName,
6419 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006420
6421 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006422 if (IsLocalFriend)
6423 SemaRef.LookupName(Prev, S);
6424 else
6425 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006426 assert(!Prev.isAmbiguous() &&
6427 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006428 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006429 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00006430 MD ? MD->getParent() : nullptr);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006431 if (!Prev.empty()) {
6432 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6433 Func != FuncEnd; ++Func) {
6434 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006435 if (FD &&
6436 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006437 // Add 1 to the index so that 0 can mean the mismatch didn't
6438 // involve a parameter
6439 unsigned ParamNum =
6440 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6441 NearMatches.push_back(std::make_pair(FD, ParamNum));
6442 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006443 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006444 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006445 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006446 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6447 &ExtraArgs.D.getCXXScopeSpec(), Validator,
Craig Topperc3ec1492014-05-26 06:22:03 +00006448 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006449 // Set up everything for the call to ActOnFunctionDeclarator
6450 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6451 ExtraArgs.D.getIdentifierLoc());
6452 Previous.clear();
6453 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006454 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6455 CDeclEnd = Correction.end();
6456 CDecl != CDeclEnd; ++CDecl) {
6457 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006458 if (FD && !FD->hasBody() &&
6459 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006460 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006461 }
6462 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006463 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006464
6465 NamedDecl *Result;
6466 // Retry building the function declaration with the new previous
6467 // declarations, and with errors suppressed.
6468 {
6469 // Trap errors.
6470 Sema::SFINAETrap Trap(SemaRef);
6471
6472 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6473 // pieces need to verify the typo-corrected C++ declaration and hopefully
6474 // eliminate the need for the parameter pack ExtraArgs.
6475 Result = SemaRef.ActOnFunctionDeclarator(
6476 ExtraArgs.S, ExtraArgs.D,
6477 Correction.getCorrectionDecl()->getDeclContext(),
6478 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6479 ExtraArgs.AddToScope);
6480
6481 if (Trap.hasErrorOccurred())
Craig Topperc3ec1492014-05-26 06:22:03 +00006482 Result = nullptr;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006483 }
Richard Smithf9b15102013-08-17 00:46:16 +00006484
6485 if (Result) {
6486 // Determine which correction we picked.
6487 Decl *Canonical = Result->getCanonicalDecl();
6488 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6489 I != E; ++I)
6490 if ((*I)->getCanonicalDecl() == Canonical)
6491 Correction.setCorrectionDecl(*I);
6492
6493 SemaRef.diagnoseTypo(
6494 Correction,
6495 SemaRef.PDiag(IsLocalFriend
6496 ? diag::err_no_matching_local_friend_suggest
6497 : diag::err_member_decl_does_not_match_suggest)
6498 << Name << NewDC << IsDefinition);
6499 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006500 }
Richard Smithf9b15102013-08-17 00:46:16 +00006501
6502 // Pretend the typo correction never occurred
6503 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6504 ExtraArgs.D.getIdentifierLoc());
6505 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6506 Previous.clear();
6507 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006508 }
6509
Richard Smithf9b15102013-08-17 00:46:16 +00006510 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6511 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006512
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006513 bool NewFDisConst = false;
6514 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006515 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006516
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006517 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006518 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6519 NearMatch != NearMatchEnd; ++NearMatch) {
6520 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006521 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6522 bool FDisConst = MD && MD->isConst();
6523 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006524
Richard Smith541b38b2013-09-20 01:15:31 +00006525 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006526 if (unsigned Idx = NearMatch->second) {
6527 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006528 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6529 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006530 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6531 : diag::note_local_decl_close_param_match)
6532 << Idx << FDParam->getType()
6533 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006534 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006535 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006536 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006537 } else
Richard Smith114394f2013-08-09 04:35:01 +00006538 SemaRef.Diag(FD->getLocation(),
6539 IsMember ? diag::note_member_def_close_match
6540 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006541 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006542 return nullptr;
John McCallf7cfb222010-10-13 05:45:15 +00006543}
6544
David Blaikie30d15442011-10-19 22:56:21 +00006545static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6546 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006547 switch (D.getDeclSpec().getStorageClassSpec()) {
6548 default: llvm_unreachable("Unknown storage class!");
6549 case DeclSpec::SCS_auto:
6550 case DeclSpec::SCS_register:
6551 case DeclSpec::SCS_mutable:
6552 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6553 diag::err_typecheck_sclass_func);
6554 D.setInvalidType();
6555 break;
6556 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006557 case DeclSpec::SCS_extern:
6558 if (D.getDeclSpec().isExternInLinkageSpec())
6559 return SC_None;
6560 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006561 case DeclSpec::SCS_static: {
6562 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6563 // C99 6.7.1p5:
6564 // The declaration of an identifier for a function that has
6565 // block scope shall have no explicit storage-class specifier
6566 // other than extern
6567 // See also (C++ [dcl.stc]p4).
6568 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6569 diag::err_static_block_func);
6570 break;
6571 } else
6572 return SC_Static;
6573 }
6574 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6575 }
6576
6577 // No explicit storage class has already been returned
6578 return SC_None;
6579}
6580
6581static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6582 DeclContext *DC, QualType &R,
6583 TypeSourceInfo *TInfo,
6584 FunctionDecl::StorageClass SC,
6585 bool &IsVirtualOkay) {
6586 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6587 DeclarationName Name = NameInfo.getName();
6588
Craig Topperc3ec1492014-05-26 06:22:03 +00006589 FunctionDecl *NewFD = nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006590 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006591
David Blaikiebbafb8a2012-03-11 07:00:24 +00006592 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006593 // Determine whether the function was written with a
6594 // prototype. This true when:
6595 // - there is a prototype in the declarator, or
6596 // - the type R of the function is some kind of typedef or other reference
6597 // to a type name (which eventually refers to a function type).
6598 bool HasPrototype =
6599 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6600 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6601
David Blaikie30d15442011-10-19 22:56:21 +00006602 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006603 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006604 TInfo, SC, isInline,
6605 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006606 if (D.isInvalidType())
6607 NewFD->setInvalidDecl();
6608
6609 // Set the lexical context.
6610 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6611
6612 return NewFD;
6613 }
6614
6615 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6616 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6617
6618 // Check that the return type is not an abstract class type.
6619 // For record types, this is done by the AbstractClassUsageDiagnoser once
6620 // the class has been completely parsed.
6621 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006622 SemaRef.RequireNonAbstractType(
6623 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6624 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006625 D.setInvalidType();
6626
6627 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6628 // This is a C++ constructor declaration.
6629 assert(DC->isRecord() &&
6630 "Constructors can only be declared in a member context");
6631
6632 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6633 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006634 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006635 R, TInfo, isExplicit, isInline,
6636 /*isImplicitlyDeclared=*/false,
6637 isConstexpr);
6638
6639 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6640 // This is a C++ destructor declaration.
6641 if (DC->isRecord()) {
6642 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6643 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6644 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6645 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006646 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006647 NameInfo, R, TInfo, isInline,
6648 /*isImplicitlyDeclared=*/false);
6649
6650 // If the class is complete, then we now create the implicit exception
6651 // specification. If the class is incomplete or dependent, we can't do
6652 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006653 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006654 Record->getDefinition() && !Record->isBeingDefined() &&
6655 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6656 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6657 }
6658
6659 IsVirtualOkay = true;
6660 return NewDD;
6661
6662 } else {
6663 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6664 D.setInvalidType();
6665
6666 // Create a FunctionDecl to satisfy the function definition parsing
6667 // code path.
6668 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006669 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006670 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006671 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006672 /*hasPrototype=*/true, isConstexpr);
6673 }
6674
6675 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6676 if (!DC->isRecord()) {
6677 SemaRef.Diag(D.getIdentifierLoc(),
6678 diag::err_conv_function_not_member);
Craig Topperc3ec1492014-05-26 06:22:03 +00006679 return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006680 }
6681
6682 SemaRef.CheckConversionDeclarator(D, R, SC);
6683 IsVirtualOkay = true;
6684 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006685 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006686 R, TInfo, isInline, isExplicit,
6687 isConstexpr, SourceLocation());
6688
6689 } else if (DC->isRecord()) {
6690 // If the name of the function is the same as the name of the record,
6691 // then this must be an invalid constructor that has a return type.
6692 // (The parser checks for a return type and makes the declarator a
6693 // constructor if it has no return type).
6694 if (Name.getAsIdentifierInfo() &&
6695 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6696 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6697 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6698 << SourceRange(D.getIdentifierLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +00006699 return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006700 }
6701
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006702 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006703 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6704 cast<CXXRecordDecl>(DC),
6705 D.getLocStart(), NameInfo, R,
6706 TInfo, SC, isInline,
6707 isConstexpr, SourceLocation());
6708 IsVirtualOkay = !Ret->isStatic();
6709 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006710 } else {
6711 // Determine whether the function was written with a
6712 // prototype. This true when:
6713 // - we're in C++ (where every function has a prototype),
6714 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006715 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006716 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006717 true/*HasPrototype*/, isConstexpr);
6718 }
6719}
6720
Matt Arsenaultefb38192013-07-23 01:23:36 +00006721enum OpenCLParamType {
6722 ValidKernelParam,
6723 PtrPtrKernelParam,
6724 PtrKernelParam,
David Tweedababa8f2014-03-27 16:34:11 +00006725 PrivatePtrKernelParam,
Matt Arsenaultefb38192013-07-23 01:23:36 +00006726 InvalidKernelParam,
6727 RecordKernelParam
6728};
6729
6730static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6731 if (PT->isPointerType()) {
6732 QualType PointeeType = PT->getPointeeType();
David Tweedababa8f2014-03-27 16:34:11 +00006733 if (PointeeType->isPointerType())
6734 return PtrPtrKernelParam;
6735 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6736 : PtrKernelParam;
Matt Arsenaultefb38192013-07-23 01:23:36 +00006737 }
6738
6739 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6740 // be used as builtin types.
6741
6742 if (PT->isImageType())
6743 return PtrKernelParam;
6744
6745 if (PT->isBooleanType())
6746 return InvalidKernelParam;
6747
6748 if (PT->isEventT())
6749 return InvalidKernelParam;
6750
6751 if (PT->isHalfType())
6752 return InvalidKernelParam;
6753
6754 if (PT->isRecordType())
6755 return RecordKernelParam;
6756
6757 return ValidKernelParam;
6758}
6759
6760static void checkIsValidOpenCLKernelParameter(
6761 Sema &S,
6762 Declarator &D,
6763 ParmVarDecl *Param,
Craig Topper4dd9b432014-08-17 23:49:53 +00006764 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006765 QualType PT = Param->getType();
6766
6767 // Cache the valid types we encounter to avoid rechecking structs that are
6768 // used again
6769 if (ValidTypes.count(PT.getTypePtr()))
6770 return;
6771
6772 switch (getOpenCLKernelParameterType(PT)) {
6773 case PtrPtrKernelParam:
6774 // OpenCL v1.2 s6.9.a:
6775 // A kernel function argument cannot be declared as a
6776 // pointer to a pointer type.
6777 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6778 D.setInvalidType();
6779 return;
6780
David Tweedababa8f2014-03-27 16:34:11 +00006781 case PrivatePtrKernelParam:
6782 // OpenCL v1.2 s6.9.a:
6783 // A kernel function argument cannot be declared as a
6784 // pointer to the private address space.
6785 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6786 D.setInvalidType();
6787 return;
6788
Matt Arsenaultefb38192013-07-23 01:23:36 +00006789 // OpenCL v1.2 s6.9.k:
6790 // Arguments to kernel functions in a program cannot be declared with the
6791 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6792 // uintptr_t or a struct and/or union that contain fields declared to be
6793 // one of these built-in scalar types.
6794
6795 case InvalidKernelParam:
6796 // OpenCL v1.2 s6.8 n:
6797 // A kernel function argument cannot be declared
6798 // of event_t type.
6799 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6800 D.setInvalidType();
6801 return;
6802
6803 case PtrKernelParam:
6804 case ValidKernelParam:
6805 ValidTypes.insert(PT.getTypePtr());
6806 return;
6807
6808 case RecordKernelParam:
6809 break;
6810 }
6811
6812 // Track nested structs we will inspect
6813 SmallVector<const Decl *, 4> VisitStack;
6814
6815 // Track where we are in the nested structs. Items will migrate from
6816 // VisitStack to HistoryStack as we do the DFS for bad field.
6817 SmallVector<const FieldDecl *, 4> HistoryStack;
Craig Topperc3ec1492014-05-26 06:22:03 +00006818 HistoryStack.push_back(nullptr);
Matt Arsenaultefb38192013-07-23 01:23:36 +00006819
6820 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6821 VisitStack.push_back(PD);
6822
6823 assert(VisitStack.back() && "First decl null?");
6824
6825 do {
6826 const Decl *Next = VisitStack.pop_back_val();
6827 if (!Next) {
6828 assert(!HistoryStack.empty());
6829 // Found a marker, we have gone up a level
6830 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6831 ValidTypes.insert(Hist->getType().getTypePtr());
6832
6833 continue;
6834 }
6835
6836 // Adds everything except the original parameter declaration (which is not a
6837 // field itself) to the history stack.
6838 const RecordDecl *RD;
6839 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6840 HistoryStack.push_back(Field);
6841 RD = Field->getType()->castAs<RecordType>()->getDecl();
6842 } else {
6843 RD = cast<RecordDecl>(Next);
6844 }
6845
6846 // Add a null marker so we know when we've gone back up a level
Craig Topperc3ec1492014-05-26 06:22:03 +00006847 VisitStack.push_back(nullptr);
Matt Arsenaultefb38192013-07-23 01:23:36 +00006848
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006849 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006850 QualType QT = FD->getType();
6851
6852 if (ValidTypes.count(QT.getTypePtr()))
6853 continue;
6854
6855 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6856 if (ParamType == ValidKernelParam)
6857 continue;
6858
6859 if (ParamType == RecordKernelParam) {
6860 VisitStack.push_back(FD);
6861 continue;
6862 }
6863
6864 // OpenCL v1.2 s6.9.p:
6865 // Arguments to kernel functions that are declared to be a struct or union
6866 // do not allow OpenCL objects to be passed as elements of the struct or
6867 // union.
David Tweedababa8f2014-03-27 16:34:11 +00006868 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6869 ParamType == PrivatePtrKernelParam) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006870 S.Diag(Param->getLocation(),
6871 diag::err_record_with_pointers_kernel_param)
6872 << PT->isUnionType()
6873 << PT;
6874 } else {
6875 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6876 }
6877
6878 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6879 << PD->getDeclName();
6880
6881 // We have an error, now let's go back up through history and show where
6882 // the offending field came from
6883 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6884 E = HistoryStack.end(); I != E; ++I) {
6885 const FieldDecl *OuterField = *I;
6886 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6887 << OuterField->getType();
6888 }
6889
6890 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6891 << QT->isPointerType()
6892 << QT;
6893 D.setInvalidType();
6894 return;
6895 }
6896 } while (!VisitStack.empty());
6897}
6898
Mike Stump11289f42009-09-09 15:08:12 +00006899NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006900Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006901 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006902 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006903 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006904 QualType R = TInfo->getType();
6905
Zhongxing Xubece5d62009-01-16 01:13:29 +00006906 assert(R.getTypePtr()->isFunctionType());
6907
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006908 // TODO: consider using NameInfo for diagnostic.
6909 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6910 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006911 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006912
Richard Smithb4a9e862013-04-12 22:46:28 +00006913 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6914 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6915 diag::err_invalid_thread)
6916 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006917
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006918 if (D.isFirstDeclarationOfMember())
6919 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006920
Douglas Gregor513e63c2010-12-10 19:28:19 +00006921 bool isFriend = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00006922 FunctionTemplateDecl *FunctionTemplate = nullptr;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006923 bool isExplicitSpecialization = false;
6924 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006925
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006926 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006927 bool HasExplicitTemplateArgs = false;
6928 TemplateArgumentListInfo TemplateArgs;
6929
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006930 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006931
Richard Smith541b38b2013-09-20 01:15:31 +00006932 DeclContext *OriginalDC = DC;
6933 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6934
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006935 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6936 isVirtualOkay);
Craig Topperc3ec1492014-05-26 06:22:03 +00006937 if (!NewFD) return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006938
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006939 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6940 NewFD->setTopLevelDeclInObjCContainer();
6941
Richard Smith541b38b2013-09-20 01:15:31 +00006942 // Set the lexical context. If this is a function-scope declaration, or has a
6943 // C++ scope specifier, or is the object of a friend declaration, the lexical
6944 // context will be different from the semantic context.
6945 NewFD->setLexicalDeclContext(CurContext);
6946
6947 if (IsLocalExternDecl)
6948 NewFD->setLocalExternDecl();
6949
David Blaikiebbafb8a2012-03-11 07:00:24 +00006950 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006951 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006952 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6953 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006954 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006955 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006956 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006957 // C++ [class.friend]p5
6958 // A function can be defined in a friend declaration of a
6959 // class . . . . Such a function is implicitly inline.
6960 NewFD->setImplicitlyInline();
6961 }
6962
John McCalldb632ac2012-09-25 07:32:39 +00006963 // If this is a method defined in an __interface, and is not a constructor
6964 // or an overloaded operator, then set the pure flag (isVirtual will already
6965 // return true).
6966 if (const CXXRecordDecl *Parent =
6967 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6968 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006969 NewFD->setPure(true);
6970 }
6971
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006972 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006973 isExplicitSpecialization = false;
6974 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006975 if (D.isInvalidType())
6976 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006977
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006978 // Match up the template parameter lists with the scope specifier, then
6979 // determine whether we have a template or a template specialization.
6980 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006981 if (TemplateParameterList *TemplateParams =
6982 MatchTemplateParametersToScopeSpecifier(
6983 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00006984 D.getCXXScopeSpec(),
6985 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6986 ? D.getName().TemplateId
Craig Topperc3ec1492014-05-26 06:22:03 +00006987 : nullptr,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006988 TemplateParamLists, isFriend, isExplicitSpecialization,
6989 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006990 if (TemplateParams->size() > 0) {
6991 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006992
Abramo Bagnara60804e12011-03-18 15:16:37 +00006993 // Check that we can declare a template here.
6994 if (CheckTemplateDeclScope(S, TemplateParams))
Craig Topperc3ec1492014-05-26 06:22:03 +00006995 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006996
Abramo Bagnara60804e12011-03-18 15:16:37 +00006997 // A destructor cannot be a template.
6998 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6999 Diag(NewFD->getLocation(), diag::err_destructor_template);
Craig Topperc3ec1492014-05-26 06:22:03 +00007000 return nullptr;
John McCall1f0479e2010-03-24 08:27:58 +00007001 }
Douglas Gregor041b0842011-10-14 15:31:12 +00007002
7003 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00007004 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00007005 // now that we know what the current instantiation is.
7006 if (DC->isDependentContext()) {
7007 ContextRAII SavedContext(*this, DC);
7008 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7009 Invalid = true;
7010 }
7011
John McCall1f0479e2010-03-24 08:27:58 +00007012
Abramo Bagnara60804e12011-03-18 15:16:37 +00007013 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7014 NewFD->getLocation(),
7015 Name, TemplateParams,
7016 NewFD);
7017 FunctionTemplate->setLexicalDeclContext(CurContext);
7018 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7019
7020 // For source fidelity, store the other template param lists.
7021 if (TemplateParamLists.size() > 1) {
7022 NewFD->setTemplateParameterListsInfo(Context,
7023 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007024 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00007025 }
7026 } else {
7027 // This is a function template specialization.
7028 isFunctionTemplateSpecialization = true;
7029 // For source fidelity, store all the template param lists.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007030 if (TemplateParamLists.size() > 0)
7031 NewFD->setTemplateParameterListsInfo(Context,
7032 TemplateParamLists.size(),
7033 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00007034
7035 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7036 if (isFriend) {
7037 // We want to remove the "template<>", found here.
7038 SourceRange RemoveRange = TemplateParams->getSourceRange();
7039
7040 // If we remove the template<> and the name is not a
7041 // template-id, we're actually silently creating a problem:
7042 // the friend declaration will refer to an untemplated decl,
7043 // and clearly the user wants a template specialization. So
7044 // we need to insert '<>' after the name.
7045 SourceLocation InsertLoc;
7046 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7047 InsertLoc = D.getName().getSourceRange().getEnd();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007048 InsertLoc = getLocForEndOfToken(InsertLoc);
Abramo Bagnara60804e12011-03-18 15:16:37 +00007049 }
7050
7051 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7052 << Name << RemoveRange
7053 << FixItHint::CreateRemoval(RemoveRange)
7054 << FixItHint::CreateInsertion(InsertLoc, "<>");
7055 }
7056 }
7057 }
7058 else {
7059 // All template param lists were matched against the scope specifier:
7060 // this is NOT (an explicit specialization of) a template.
7061 if (TemplateParamLists.size() > 0)
7062 // For source fidelity, store all the template param lists.
7063 NewFD->setTemplateParameterListsInfo(Context,
7064 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007065 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007066 }
7067
7068 if (Invalid) {
7069 NewFD->setInvalidDecl();
7070 if (FunctionTemplate)
7071 FunctionTemplate->setInvalidDecl();
7072 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007073
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007074 // C++ [dcl.fct.spec]p5:
7075 // The virtual specifier shall only be used in declarations of
7076 // nonstatic class member functions that appear within a
7077 // member-specification of a class declaration; see 10.3.
7078 //
7079 if (isVirtual && !NewFD->isInvalidDecl()) {
7080 if (!isVirtualOkay) {
7081 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7082 diag::err_virtual_non_function);
7083 } else if (!CurContext->isRecord()) {
7084 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00007085 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7086 diag::err_virtual_out_of_class)
7087 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7088 } else if (NewFD->getDescribedFunctionTemplate()) {
7089 // C++ [temp.mem]p3:
7090 // A member function template shall not be virtual.
7091 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7092 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007093 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7094 } else {
7095 // Okay: Add virtual to the method.
7096 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00007097 }
Richard Smith2a7d4812013-05-04 07:00:32 +00007098
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007099 if (getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00007100 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00007101 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00007102 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007103
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007104 if (getLangOpts().CPlusPlus14 &&
Richard Smithc1564702013-11-15 02:58:23 +00007105 (NewFD->isDependentContext() ||
7106 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00007107 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00007108 // If the function template is referenced directly (for instance, as a
7109 // member of the current instantiation), pretend it has a dependent type.
7110 // This is not really justified by the standard, but is the only sane
7111 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00007112 // FIXME: For a friend function, we have not marked the function as being
7113 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00007114 const FunctionProtoType *FPT =
7115 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007116 QualType Result =
7117 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00007118 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00007119 FPT->getExtProtoInfo()));
7120 }
7121
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007122 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00007123 // The inline specifier shall not appear on a block scope function
7124 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007125 if (isInline && !NewFD->isInvalidDecl()) {
7126 if (CurContext->isFunctionOrMethod()) {
7127 // 'inline' is not allowed on block scope function declaration.
7128 Diag(D.getDeclSpec().getInlineSpecLoc(),
7129 diag::err_inline_declaration_block_scope) << Name
7130 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7131 }
7132 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007133
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007134 // C++ [dcl.fct.spec]p6:
7135 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00007136 // constructor or conversion function within its class definition;
7137 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007138 if (isExplicit && !NewFD->isInvalidDecl()) {
7139 if (!CurContext->isRecord()) {
7140 // 'explicit' was specified outside of the class.
7141 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7142 diag::err_explicit_out_of_class)
7143 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7144 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7145 !isa<CXXConversionDecl>(NewFD)) {
7146 // 'explicit' was specified on a function that wasn't a constructor
7147 // or conversion function.
7148 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7149 diag::err_explicit_non_ctor_or_conv_function)
7150 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7151 }
7152 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007153
Richard Smitha77a0a62011-08-15 21:04:07 +00007154 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00007155 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00007156 // are implicitly inline.
7157 NewFD->setImplicitlyInline();
7158
Richard Smith574f4f62013-01-14 05:37:29 +00007159 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00007160 // be either constructors or to return a literal type. Therefore,
7161 // destructors cannot be declared constexpr.
7162 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00007163 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00007164 }
7165
Douglas Gregor26701a42011-09-09 02:06:17 +00007166 // If __module_private__ was specified, mark the function accordingly.
7167 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00007168 if (isFunctionTemplateSpecialization) {
7169 SourceLocation ModulePrivateLoc
7170 = D.getDeclSpec().getModulePrivateSpecLoc();
7171 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7172 << 0
7173 << FixItHint::CreateRemoval(ModulePrivateLoc);
7174 } else {
7175 NewFD->setModulePrivate();
7176 if (FunctionTemplate)
7177 FunctionTemplate->setModulePrivate();
7178 }
Douglas Gregor26701a42011-09-09 02:06:17 +00007179 }
Richard Smitha77a0a62011-08-15 21:04:07 +00007180
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007181 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007182 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00007183 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007184 FunctionTemplate->setAccess(AS_public);
7185 }
Richard Smith64017682013-07-17 23:53:16 +00007186 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007187 NewFD->setAccess(AS_public);
7188 }
7189
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007190 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00007191 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7192 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007193 switch (D.getFunctionDefinitionKind()) {
7194 case FDK_Declaration:
7195 case FDK_Definition:
7196 break;
7197
7198 case FDK_Defaulted:
7199 NewFD->setDefaulted();
7200 break;
7201
7202 case FDK_Deleted:
7203 NewFD->setDeletedAsWritten();
7204 break;
7205 }
7206
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007207 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7208 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007209 // C++ [class.mfct]p2:
7210 // A member function may be defined (8.4) in its class definition, in
7211 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00007212 NewFD->setImplicitlyInline();
7213 }
7214
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007215 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7216 !CurContext->isRecord()) {
7217 // C++ [class.static]p1:
7218 // A data or function member of a class may be declared static
7219 // in a class definition, in which case it is a static member of
7220 // the class.
7221
7222 // Complain about the 'static' specifier if it's on an out-of-line
7223 // member function definition.
7224 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7225 diag::err_static_out_of_line)
7226 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7227 }
Richard Smith66f3ac92012-10-20 08:26:51 +00007228
7229 // C++11 [except.spec]p15:
7230 // A deallocation function with no exception-specification is treated
7231 // as if it were specified with noexcept(true).
7232 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7233 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7234 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith8acb4282014-07-31 21:57:55 +00007235 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7236 NewFD->setType(Context.getFunctionType(
7237 FPT->getReturnType(), FPT->getParamTypes(),
7238 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007239 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007240
7241 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00007242 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00007243 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007244 isExplicitSpecialization ||
7245 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00007246
Zhongxing Xubece5d62009-01-16 01:13:29 +00007247 // Handle GNU asm-label extension (encoded as an attribute).
7248 if (Expr *E = (Expr*) D.getAsmLabel()) {
7249 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00007250 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007251 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00007252 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00007253 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7254 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7255 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7256 if (I != ExtnameUndeclaredIdentifiers.end()) {
7257 NewFD->addAttr(I->second);
7258 ExtnameUndeclaredIdentifiers.erase(I);
7259 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007260 }
7261
Chris Lattner9af40c12009-04-25 06:12:16 +00007262 // Copy the parameter declarations from the declarator D to the function
7263 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007264 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00007265 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007266 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00007267
Zhongxing Xubece5d62009-01-16 01:13:29 +00007268 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7269 // function that takes no arguments, not a function that takes a
7270 // single void argument.
7271 // We let through "const void" here because Sema::GetTypeForDeclarator
7272 // already checks for that case.
Alp Toker4284c6e2014-05-11 16:05:55 +00007273 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
Alp Tokerc5350722014-02-26 22:27:52 +00007274 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7275 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007276 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7277 Param->setDeclContext(NewFD);
7278 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00007279
7280 if (Param->isInvalidDecl())
7281 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007282 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007283 }
Mike Stump11289f42009-09-09 15:08:12 +00007284
John McCall9dd450b2009-09-21 23:43:11 +00007285 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00007286 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00007287 // following example, we'll need to synthesize (unnamed)
7288 // parameters for use in the declaration.
7289 //
7290 // @code
7291 // typedef void fn(int);
7292 // fn f;
7293 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00007294
Chris Lattner47c0d002009-04-25 06:03:53 +00007295 // Synthesize a parameter for each argument type.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007296 for (const auto &AI : FT->param_types()) {
John McCalla3ccba02010-06-04 11:21:44 +00007297 ParmVarDecl *Param =
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007298 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00007299 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00007300 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00007301 }
Chris Lattner49303b22009-04-25 18:38:18 +00007302 } else {
7303 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7304 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00007305 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00007306
Chris Lattner9af40c12009-04-25 06:12:16 +00007307 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00007308 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00007309
James Molloy6f8780b2012-02-29 10:24:19 +00007310 // Find all anonymous symbols defined during the declaration of this function
7311 // and add to NewFD. This lets us track decls such 'enum Y' in:
7312 //
7313 // void f(enum Y {AA} x) {}
7314 //
7315 // which would otherwise incorrectly end up in the translation unit scope.
7316 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7317 DeclsInPrototypeScope.clear();
7318
Richard Smithdebc59d2013-01-30 05:45:05 +00007319 if (D.getDeclSpec().isNoreturnSpecified())
7320 NewFD->addAttr(
7321 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00007322 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00007323
Richard Smith84208dc2012-03-13 05:56:40 +00007324 // Functions returning a variably modified type violate C99 6.7.5.2p2
7325 // because all functions have linkage.
7326 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00007327 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00007328 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7329 NewFD->setInvalidDecl();
7330 }
7331
Warren Huntc3b18962014-04-08 22:30:47 +00007332 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7333 !NewFD->hasAttr<SectionAttr>()) {
7334 NewFD->addAttr(
7335 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7336 CodeSegStack.CurrentValue->getString(),
7337 CodeSegStack.CurrentPragmaLocation));
7338 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7339 PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7340 NewFD->dropAttr<SectionAttr>();
7341 }
7342
Rafael Espindolac67f2232012-05-10 02:50:16 +00007343 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00007344 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00007345
Alp Toker314cc812014-01-25 16:55:45 +00007346 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007347 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7348 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7349 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7350 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007351 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
David Blaikie080a61c2014-02-09 07:24:41 +00007352 // Attach WarnUnusedResult to functions returning types with that attribute.
7353 // Don't apply the attribute to that type's own non-static member functions
7354 // (to avoid warning on things like assignment operators)
7355 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00007356 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007357 }
7358
Joey Gouly16cb99d2014-01-06 11:26:18 +00007359 if (getLangOpts().OpenCL) {
7360 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7361 // type declaration will generate a compilation error.
7362 unsigned AddressSpace = RetType.getAddressSpace();
7363 if (AddressSpace == LangAS::opencl_local ||
7364 AddressSpace == LangAS::opencl_global ||
7365 AddressSpace == LangAS::opencl_constant) {
7366 Diag(NewFD->getLocation(),
7367 diag::err_opencl_return_value_with_address_space);
7368 NewFD->setInvalidDecl();
7369 }
7370 }
7371
David Blaikiebbafb8a2012-03-11 07:00:24 +00007372 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007373 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007374 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007375 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7376 CheckMain(NewFD, D.getDeclSpec());
7377
David Majnemerc729b0b2013-09-16 22:44:20 +00007378 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7379 CheckMSVCRTEntryPoint(NewFD);
7380
David Majnemer027f9c42013-07-06 02:13:46 +00007381 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007382 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7383 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007384 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007385 // Make graceful recovery from an invalid redeclaration.
7386 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007387 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007388 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7389 "previous declaration set still overloaded");
7390 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007391 // C++11 [replacement.functions]p3:
7392 // The program's definitions shall not be specified as inline.
7393 //
7394 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7395 //
7396 // Suppress the diagnostic if the function is __attribute__((used)), since
7397 // that forces an external definition to be emitted.
7398 if (D.getDeclSpec().isInlineSpecified() &&
7399 NewFD->isReplaceableGlobalAllocationFunction() &&
7400 !NewFD->hasAttr<UsedAttr>())
7401 Diag(D.getDeclSpec().getInlineSpecLoc(),
7402 diag::ext_operator_new_delete_declared_inline)
7403 << NewFD->getDeclName();
7404
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007405 // If the declarator is a template-id, translate the parser's template
7406 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007407 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7408 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7409 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7410 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007411 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007412 TemplateId->NumArgs);
7413 translateTemplateArguments(TemplateArgsPtr,
7414 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007415
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007416 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007417
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007418 if (NewFD->isInvalidDecl()) {
7419 HasExplicitTemplateArgs = false;
7420 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007421 // Function template with explicit template arguments.
7422 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7423 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7424
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007425 HasExplicitTemplateArgs = false;
John McCallf7cfb222010-10-13 05:45:15 +00007426 } else {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007427 assert((isFunctionTemplateSpecialization ||
7428 D.getDeclSpec().isFriendSpecified()) &&
7429 "should have a 'template<>' for this decl");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007430 // "friend void foo<>(int);" is an implicit specialization decl.
7431 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007432 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007433 } else if (isFriend && isFunctionTemplateSpecialization) {
7434 // This combination is only possible in a recovery case; the user
7435 // wrote something like:
7436 // template <> friend void foo(int);
7437 // which we're recovering from as if the user had written:
7438 // friend void foo<>(int);
7439 // Go ahead and fake up a template id.
7440 HasExplicitTemplateArgs = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00007441 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007442 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007443 }
John McCallf7cfb222010-10-13 05:45:15 +00007444
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007445 // If it's a friend (and only if it's a friend), it's possible
7446 // that either the specialized function type or the specialized
7447 // template is dependent, and therefore matching will fail. In
7448 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007449 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007450 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007451 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7452 TemplateSpecializationType::anyDependentTemplateArguments(
7453 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7454 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007455 assert(HasExplicitTemplateArgs &&
7456 "friend function specialization without template args");
7457 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7458 Previous))
7459 NewFD->setInvalidDecl();
7460 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007461 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007462 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007463 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007464 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007465 diag::ext_function_specialization_in_class :
7466 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007467 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007468 } else if (CheckFunctionTemplateSpecialization(NewFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00007469 (HasExplicitTemplateArgs ? &TemplateArgs
7470 : nullptr),
Douglas Gregor63fab342011-03-16 19:27:09 +00007471 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007472 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007473
7474 // C++ [dcl.stc]p1:
7475 // A storage-class-specifier shall not be specified in an explicit
7476 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007477 FunctionTemplateSpecializationInfo *Info =
7478 NewFD->getTemplateSpecializationInfo();
7479 if (Info && SC != SC_None) {
7480 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007481 Diag(NewFD->getLocation(),
7482 diag::err_explicit_specialization_inconsistent_storage_class)
7483 << SC
7484 << FixItHint::CreateRemoval(
7485 D.getDeclSpec().getStorageClassSpecLoc());
7486
7487 else
7488 Diag(NewFD->getLocation(),
7489 diag::ext_explicit_specialization_storage_class)
7490 << FixItHint::CreateRemoval(
7491 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007492 }
7493
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007494 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7495 if (CheckMemberSpecialization(NewFD, Previous))
7496 NewFD->setInvalidDecl();
7497 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007498
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007499 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007500 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007501 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7502 CheckMain(NewFD, D.getDeclSpec());
7503
David Majnemerc729b0b2013-09-16 22:44:20 +00007504 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7505 CheckMSVCRTEntryPoint(NewFD);
7506
Nico Weber7607fce2013-12-21 00:49:51 +00007507 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007508 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7509 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007510 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007511
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007512 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007513 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7514 "previous declaration set still overloaded");
7515
7516 NamedDecl *PrincipalDecl = (FunctionTemplate
7517 ? cast<NamedDecl>(FunctionTemplate)
7518 : NewFD);
7519
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007520 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007521 AccessSpecifier Access = AS_public;
7522 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007523 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007524
7525 NewFD->setAccess(Access);
7526 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007527 }
7528
7529 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7530 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7531 PrincipalDecl->setNonMemberOperator();
7532
7533 // If we have a function template, check the template parameter
7534 // list. This will check and merge default template arguments.
7535 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007536 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007537 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007538 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007539 PrevTemplate ? PrevTemplate->getTemplateParameters()
7540 : nullptr,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007541 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007542 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007543 ? TPC_FriendFunctionTemplateDefinition
7544 : TPC_FriendFunctionTemplate)
7545 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007546 DC && DC->isRecord() &&
7547 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007548 ? TPC_ClassTemplateMember
7549 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007550 }
7551
7552 if (NewFD->isInvalidDecl()) {
7553 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007554 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007555 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007556 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007557 // Fake up an access specifier if it's supposed to be a class member.
7558 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7559 NewFD->setAccess(AS_public);
7560
7561 // Qualified decls generally require a previous declaration.
7562 if (D.getCXXScopeSpec().isSet()) {
7563 // ...with the major exception of templated-scope or
7564 // dependent-scope friend declarations.
7565
7566 // TODO: we currently also suppress this check in dependent
7567 // contexts because (1) the parameter depth will be off when
7568 // matching friend templates and (2) we might actually be
7569 // selecting a friend based on a dependent factor. But there
7570 // are situations where these conditions don't apply and we
7571 // can actually do this check immediately.
7572 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007573 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007574 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7575 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007576 // ignore these
7577 } else {
7578 // The user tried to provide an out-of-line definition for a
7579 // function that is a member of a class or namespace, but there
7580 // was no such member function declared (C++ [class.mfct]p2,
7581 // C++ [namespace.memdef]p2). For example:
7582 //
7583 // class X {
7584 // void f() const;
7585 // };
7586 //
7587 // void X::f() { } // ill-formed
7588 //
7589 // Complain about this problem, and attempt to suggest close
7590 // matches (e.g., those that differ only in cv-qualifiers and
7591 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007592
Richard Smith114394f2013-08-09 04:35:01 +00007593 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
Craig Topperc3ec1492014-05-26 06:22:03 +00007594 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007595 AddToScope = ExtraArgs.AddToScope;
7596 return Result;
7597 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007598 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007599
7600 // Unqualified local friend declarations are required to resolve
7601 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007602 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007603 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7604 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007605 AddToScope = ExtraArgs.AddToScope;
7606 return Result;
7607 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007608 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007609
Richard Smitha2302242013-12-05 07:51:02 +00007610 } else if (!D.isFunctionDefinition() &&
7611 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007612 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007613 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007614 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007615 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007616 // Note that this is not the case for explicit specializations of
7617 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007618 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7619 // extension for compatibility with old SWIG code which likes to
7620 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007621 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7622 << D.getCXXScopeSpec().getRange();
7623 }
7624 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007625
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007626 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007627 checkAttributesAfterMerging(*this, *NewFD);
7628
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007629 AddKnownFunctionAttributes(NewFD);
7630
Douglas Gregor72609052010-08-06 13:50:58 +00007631 if (NewFD->hasAttr<OverloadableAttr>() &&
7632 !NewFD->getType()->getAs<FunctionProtoType>()) {
7633 Diag(NewFD->getLocation(),
7634 diag::err_attribute_overloadable_no_prototype)
7635 << NewFD;
7636
7637 // Turn this into a variadic function with no parameters.
7638 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007639 FunctionProtoType::ExtProtoInfo EPI(
7640 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007641 EPI.Variadic = true;
7642 EPI.ExtInfo = FT->getExtInfo();
7643
Alp Toker314cc812014-01-25 16:55:45 +00007644 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007645 NewFD->setType(R);
7646 }
7647
Eli Friedman570024a2010-08-05 06:57:20 +00007648 // If there's a #pragma GCC visibility in scope, and this isn't a class
7649 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007650 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007651 AddPushedVisibilityAttribute(NewFD);
7652
John McCall32f5fe12011-09-30 05:12:12 +00007653 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7654 // marking the function.
7655 AddCFAuditedAttribute(NewFD);
7656
Dario Domizioli13a0a382014-05-23 12:13:25 +00007657 // If this is a function definition, check if we have to apply optnone due to
7658 // a pragma.
7659 if(D.isFunctionDefinition())
7660 AddRangeBasedOptnone(NewFD);
7661
Richard Smithac974a32013-06-30 09:48:50 +00007662 // If this is the first declaration of an extern C variable, update
7663 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007664 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007665 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007666 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007667
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007668 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007669 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007670
Nico Rieck82f0b062014-03-31 14:56:15 +00007671 if (D.isRedeclaration() && !Previous.empty()) {
7672 checkDLLAttributeRedeclaration(
7673 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7674 isExplicitSpecialization || isFunctionTemplateSpecialization);
7675 }
7676
David Blaikiebbafb8a2012-03-11 07:00:24 +00007677 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007678 if (FunctionTemplate) {
7679 if (NewFD->isInvalidDecl())
7680 FunctionTemplate->setInvalidDecl();
7681 return FunctionTemplate;
7682 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007683 }
Mike Stump11289f42009-09-09 15:08:12 +00007684
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007685 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007686 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7687 if ((getLangOpts().OpenCLVersion >= 120)
7688 && (SC == SC_Static)) {
7689 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7690 D.setInvalidType();
7691 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007692
7693 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007694 if (!NewFD->getReturnType()->isVoidType()) {
Alp Tokerd0787eb2014-07-02 01:47:15 +00007695 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7696 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7697 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7698 : FixItHint());
Tanya Lattner0f864332013-01-30 19:48:52 +00007699 D.setInvalidType();
7700 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007701
7702 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007703 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007704 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007705 }
7706
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007707 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007708
David Blaikiebbafb8a2012-03-11 07:00:24 +00007709 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007710 if (IdentifierInfo *II = NewFD->getIdentifier())
7711 if (!NewFD->isInvalidDecl() &&
7712 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7713 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007714 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007715 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7716
7717 Context.setcudaConfigureCallDecl(NewFD);
7718 }
7719 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007720
7721 // Here we have an function template explicit specialization at class scope.
7722 // The actually specialization will be postponed to template instatiation
7723 // time via the ClassScopeFunctionSpecializationDecl node.
7724 if (isDependentClassScopeExplicitSpecialization) {
7725 ClassScopeFunctionSpecializationDecl *NewSpec =
7726 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007727 Context, CurContext, SourceLocation(),
7728 cast<CXXMethodDecl>(NewFD),
7729 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007730 CurContext->addDecl(NewSpec);
7731 AddToScope = false;
7732 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007733
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007734 return NewFD;
7735}
7736
7737/// \brief Perform semantic checking of a new function declaration.
7738///
7739/// Performs semantic analysis of the new function declaration
7740/// NewFD. This routine performs all semantic checking that does not
7741/// require the actual declarator involved in the declaration, and is
7742/// used both for the declaration of functions as they are parsed
7743/// (called via ActOnDeclarator) and for the declaration of functions
7744/// that have been instantiated via C++ template instantiation (called
7745/// via InstantiateDecl).
7746///
James Dennettffad8b72012-06-22 08:10:18 +00007747/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007748/// an explicit specialization of the previous declaration.
7749///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007750/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007751///
James Dennettffad8b72012-06-22 08:10:18 +00007752/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007753bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007754 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007755 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007756 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7757 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007758
Richard Smith1c34fb72013-08-13 18:18:50 +00007759 // Determine whether the type of this function should be merged with
7760 // a previous visible declaration. This never happens for functions in C++,
7761 // and always happens in C if the previous declaration was visible.
7762 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7763 !Previous.isShadowed();
7764
Douglas Gregor3552dab2013-01-09 00:47:56 +00007765 // Filter out any non-conflicting previous declarations.
7766 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7767
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007768 bool Redeclaration = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00007769 NamedDecl *OldDecl = nullptr;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007770
Douglas Gregore62c0a42009-02-24 01:23:02 +00007771 // Merge or overload the declaration with an existing declaration of
7772 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007773 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007774 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007775 // a declaration that requires merging. If it's an overload,
7776 // there's no more work to do here; we'll just add the new
7777 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007778 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007779 NamedDecl *Candidate = Previous.getFoundDecl();
7780 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7781 Redeclaration = true;
7782 OldDecl = Candidate;
7783 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007784 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007785 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7786 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007787 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007788 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007789 break;
7790
7791 case Ovl_NonFunction:
7792 Redeclaration = true;
7793 break;
7794
7795 case Ovl_Overload:
7796 Redeclaration = false;
7797 break;
John McCall1f82f242009-11-18 22:49:29 +00007798 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007799
David Blaikiebbafb8a2012-03-11 07:00:24 +00007800 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007801 // If a function name is overloadable in C, then every function
7802 // with that name must be marked "overloadable".
7803 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7804 << Redeclaration << NewFD;
Craig Topperc3ec1492014-05-26 06:22:03 +00007805 NamedDecl *OverloadedDecl = nullptr;
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007806 if (Redeclaration)
7807 OverloadedDecl = OldDecl;
7808 else if (!Previous.empty())
7809 OverloadedDecl = Previous.getRepresentativeDecl();
7810 if (OverloadedDecl)
7811 Diag(OverloadedDecl->getLocation(),
7812 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007813 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007814 }
John McCall1f82f242009-11-18 22:49:29 +00007815 }
Richard Smith574f4f62013-01-14 05:37:29 +00007816 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007817
Richard Smithac974a32013-06-30 09:48:50 +00007818 // Check for a previous extern "C" declaration with this name.
7819 if (!Redeclaration &&
7820 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7821 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7822 if (!Previous.empty()) {
7823 // This is an extern "C" declaration with the same name as a previous
7824 // declaration, and thus redeclares that entity...
7825 Redeclaration = true;
7826 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007827 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007828
7829 // ... except in the presence of __attribute__((overloadable)).
7830 if (OldDecl->hasAttr<OverloadableAttr>()) {
7831 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7832 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7833 << Redeclaration << NewFD;
7834 Diag(Previous.getFoundDecl()->getLocation(),
7835 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007836 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007837 }
7838 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7839 Redeclaration = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00007840 OldDecl = nullptr;
Richard Smithac974a32013-06-30 09:48:50 +00007841 }
7842 }
7843 }
7844 }
7845
Richard Smith574f4f62013-01-14 05:37:29 +00007846 // C++11 [dcl.constexpr]p8:
7847 // A constexpr specifier for a non-static member function that is not
7848 // a constructor declares that member function to be const.
7849 //
7850 // This needs to be delayed until we know whether this is an out-of-line
7851 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007852 //
7853 // This rule is not present in C++1y, so we produce a backwards
7854 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007855 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007856 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
Richard Smith034185c2013-04-21 01:08:50 +00007857 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007858 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007859 CXXMethodDecl *OldMD = nullptr;
Alp Tokera2794f92014-01-22 07:29:52 +00007860 if (OldDecl)
7861 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007862 if (!OldMD || !OldMD->isStatic()) {
7863 const FunctionProtoType *FPT =
7864 MD->getType()->castAs<FunctionProtoType>();
7865 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7866 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007867 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007868 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007869
7870 // Warn that we did this, if we're not performing template instantiation.
7871 // In that case, we'll have warned already when the template was defined.
7872 if (ActiveTemplateInstantiations.empty()) {
7873 SourceLocation AddConstLoc;
7874 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7875 .IgnoreParens().getAs<FunctionTypeLoc>())
Alp Tokerb6cc5922014-05-03 03:45:55 +00007876 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
Richard Smith034185c2013-04-21 01:08:50 +00007877
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007878 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
Richard Smith034185c2013-04-21 01:08:50 +00007879 << FixItHint::CreateInsertion(AddConstLoc, " const");
7880 }
Richard Smith574f4f62013-01-14 05:37:29 +00007881 }
7882 }
7883
7884 if (Redeclaration) {
7885 // NewFD and OldDecl represent declarations that need to be
7886 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007887 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007888 NewFD->setInvalidDecl();
7889 return Redeclaration;
7890 }
7891
7892 Previous.clear();
7893 Previous.addDecl(OldDecl);
7894
7895 if (FunctionTemplateDecl *OldTemplateDecl
7896 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7897 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7898 FunctionTemplateDecl *NewTemplateDecl
7899 = NewFD->getDescribedFunctionTemplate();
7900 assert(NewTemplateDecl && "Template/non-template mismatch");
7901 if (CXXMethodDecl *Method
7902 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7903 Method->setAccess(OldTemplateDecl->getAccess());
7904 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007905 }
Richard Smith574f4f62013-01-14 05:37:29 +00007906
7907 // If this is an explicit specialization of a member that is a function
7908 // template, mark it as a member specialization.
7909 if (IsExplicitSpecialization &&
7910 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7911 NewTemplateDecl->setMemberSpecialization();
7912 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007913 }
Richard Smith574f4f62013-01-14 05:37:29 +00007914
7915 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007916 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007917 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007918
7919 if (isa<CXXMethodDecl>(NewFD)) {
7920 // A valid redeclaration of a C++ method must be out-of-line,
7921 // but (unfortunately) it's not necessarily a definition
7922 // because of templates, which means that the previous
7923 // declaration is not necessarily from the class definition.
7924
7925 // For just setting the access, that doesn't matter.
7926 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7927 NewFD->setAccess(oldMethod->getAccess());
7928
7929 // Update the key-function state if necessary for this ABI.
7930 if (NewFD->isInlined() &&
7931 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7932 // setNonKeyFunction needs to work with the original
7933 // declaration from the class definition, and isVirtual() is
7934 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007935 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007936 if (oldMethod->isVirtual()) {
7937 Context.setNonKeyFunction(oldMethod);
7938 }
7939 }
7940 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007941 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007942 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007943
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007944 // Semantic checking for this function declaration (in isolation).
Nico Weberbe39a872014-07-31 17:19:18 +00007945
Nico Weberd1910632014-09-19 23:07:12 +00007946 // Diagnose the use of callee-cleanup calls on unprototyped functions.
Nico Weberbe39a872014-07-31 17:19:18 +00007947 QualType NewQType = Context.getCanonicalType(NewFD->getType());
7948 const FunctionType *NewType = cast<FunctionType>(NewQType);
7949 if (isa<FunctionNoProtoType>(NewType)) {
7950 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
Nico Weberd1910632014-09-19 23:07:12 +00007951 if (isCalleeCleanup(NewTypeInfo.getCC())) {
7952 // Windows system headers sometimes accidentally use stdcall without
7953 // (void) parameters, so use a default-error warning in this case :-/
7954 int DiagID = NewTypeInfo.getCC() == CC_X86StdCall
7955 ? diag::warn_cconv_knr : diag::err_cconv_knr;
7956 Diag(NewFD->getLocation(), DiagID)
7957 << FunctionType::getNameForCallConv(NewTypeInfo.getCC());
7958 }
Nico Weberbe39a872014-07-31 17:19:18 +00007959 }
7960
David Blaikiebbafb8a2012-03-11 07:00:24 +00007961 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007962 // C++-specific checks.
7963 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7964 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007965 } else if (CXXDestructorDecl *Destructor =
7966 dyn_cast<CXXDestructorDecl>(NewFD)) {
7967 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007968 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007969
Douglas Gregor7454c562010-07-02 20:37:36 +00007970 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007971 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007972 if (!ClassType->isDependentType()) {
7973 DeclarationName Name
7974 = Context.DeclarationNames.getCXXDestructorName(
7975 Context.getCanonicalType(ClassType));
7976 if (NewFD->getDeclName() != Name) {
7977 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007978 NewFD->setInvalidDecl();
7979 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007980 }
7981 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007982 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007983 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007984 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007985 }
7986
7987 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007988 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7989 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007990 !Method->getDescribedFunctionTemplate() &&
7991 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007992 if (AddOverriddenMethods(Method->getParent(), Method)) {
7993 // If the function was marked as "static", we have a problem.
7994 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007995 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007996 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007997 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007998 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007999
8000 if (Method->isStatic())
8001 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00008002 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00008003
8004 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8005 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00008006 CheckOverloadedOperatorDeclaration(NewFD)) {
8007 NewFD->setInvalidDecl();
8008 return Redeclaration;
8009 }
Alexis Huntc88db062010-01-13 09:01:02 +00008010
8011 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8012 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00008013 CheckLiteralOperatorDeclaration(NewFD)) {
8014 NewFD->setInvalidDecl();
8015 return Redeclaration;
8016 }
Alexis Huntc88db062010-01-13 09:01:02 +00008017
Anders Carlsson1b12ed42009-09-13 21:33:06 +00008018 // In C++, check default arguments now that we have merged decls. Unless
8019 // the lexical context is the class, because in this case this is done
8020 // during delayed parsing anyway.
8021 if (!CurContext->isRecord())
8022 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00008023
Douglas Gregor9246b682010-12-21 19:47:46 +00008024 // If this function declares a builtin function, check the type of this
8025 // declaration against the expected type for the builtin.
8026 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8027 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00008028 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00008029 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8030 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8031 // The type of this function differs from the type of the builtin,
8032 // so forget about the builtin entirely.
8033 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8034 }
8035 }
Warren Hunt445d83e2013-11-01 23:46:51 +00008036
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00008037 // If this function is declared as being extern "C", then check to see if
8038 // the function returns a UDT (class, struct, or union type) that is not C
8039 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00008040 // But, issue any diagnostic on the first declaration only.
8041 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00008042 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00008043 if (R->isIncompleteType() && !R->isVoidType())
8044 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8045 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00008046 else if (!R.isPODType(Context) && !R->isVoidType() &&
8047 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00008048 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00008049 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00008050 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00008051 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00008052}
8053
David Blaikied937bf12011-09-08 06:33:04 +00008054void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00008055 // C++11 [basic.start.main]p3:
8056 // A program that [...] declares main to be inline, static or
8057 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00008058 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8059 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00008060 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00008061 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00008062 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00008063 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00008064 ? diag::err_static_main : diag::warn_static_main)
8065 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8066 if (FD->isInlineSpecified())
8067 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8068 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00008069 if (DS.isNoreturnSpecified()) {
8070 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008071 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00008072 Diag(NoreturnLoc, diag::ext_noreturn_main);
8073 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8074 << FixItHint::CreateRemoval(NoreturnRange);
8075 }
Richard Smith3f333f22012-02-04 06:10:17 +00008076 if (FD->isConstexpr()) {
8077 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8078 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8079 FD->setConstexpr(false);
8080 }
John McCall02dee0a2009-07-25 04:36:53 +00008081
Joey Goulya7310a82013-11-05 12:30:39 +00008082 if (getLangOpts().OpenCL) {
8083 Diag(FD->getLocation(), diag::err_opencl_no_main)
8084 << FD->hasAttr<OpenCLKernelAttr>();
8085 FD->setInvalidDecl();
8086 return;
8087 }
8088
John McCall02dee0a2009-07-25 04:36:53 +00008089 QualType T = FD->getType();
8090 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00008091 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00008092
Alp Toker70fc29c2014-07-02 07:07:20 +00008093 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8094 // In C with GNU extensions we allow main() to have non-integer return
8095 // type, but we should warn about the extension, and we disable the
8096 // implicit-return-zero rule.
8097
8098 // GCC in C mode accepts qualified 'int'.
8099 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8100 FD->setHasImplicitReturnZero(true);
8101 else {
8102 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8103 SourceRange RTRange = FD->getReturnTypeSourceRange();
8104 if (RTRange.isValid())
8105 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8106 << FixItHint::CreateReplacement(RTRange, "int");
8107 }
8108 } else {
John McCall5ed3caf2012-02-14 19:50:52 +00008109 // In C and C++, main magically returns 0 if you fall off the end;
8110 // set the flag which tells us that.
8111 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
John McCall5ed3caf2012-02-14 19:50:52 +00008112
Alp Toker70fc29c2014-07-02 07:07:20 +00008113 // All the standards say that main() should return 'int'.
8114 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8115 FD->setHasImplicitReturnZero(true);
8116 else {
8117 // Otherwise, this is just a flat-out error.
8118 SourceRange RTRange = FD->getReturnTypeSourceRange();
8119 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8120 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8121 : FixItHint());
8122 FD->setInvalidDecl(true);
8123 }
John McCall02dee0a2009-07-25 04:36:53 +00008124 }
8125
8126 // Treat protoless main() as nullary.
8127 if (isa<FunctionNoProtoType>(FT)) return;
8128
8129 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00008130 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00008131 assert(FD->getNumParams() == nparams);
8132
John McCall0e21fcc2009-12-24 09:58:38 +00008133 bool HasExtraParameters = (nparams > 3);
8134
8135 // Darwin passes an undocumented fourth argument of type char**. If
8136 // other platforms start sprouting these, the logic below will start
8137 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00008138 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00008139 HasExtraParameters = false;
8140
8141 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00008142 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8143 FD->setInvalidDecl(true);
8144 nparams = 3;
8145 }
8146
8147 // FIXME: a lot of the following diagnostics would be improved
8148 // if we had some location information about types.
8149
8150 QualType CharPP =
8151 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00008152 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00008153
8154 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008155 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00008156
8157 bool mismatch = true;
8158
8159 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8160 mismatch = false;
8161 else if (Expected[i] == CharPP) {
8162 // As an extension, the following forms are okay:
8163 // char const **
8164 // char const * const *
8165 // char * const *
8166
John McCall8ccfcb52009-09-24 19:53:00 +00008167 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00008168 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008169 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8170 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00008171 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8172 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00008173 qs.removeConst();
8174 mismatch = !qs.empty();
8175 }
8176 }
8177
8178 if (mismatch) {
8179 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8180 // TODO: suggest replacing given type with expected type
8181 FD->setInvalidDecl(true);
8182 }
8183 }
8184
8185 if (nparams == 1 && !FD->isInvalidDecl()) {
8186 Diag(FD->getLocation(), diag::warn_main_one_arg);
8187 }
Douglas Gregorbff62032010-10-21 16:57:46 +00008188
8189 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00008190 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00008191 FD->setInvalidDecl();
8192 }
8193}
8194
8195void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8196 QualType T = FD->getType();
8197 assert(T->isFunctionType() && "function decl is not of function type");
8198 const FunctionType *FT = T->castAs<FunctionType>();
8199
8200 // Set an implicit return of 'zero' if the function can return some integral,
8201 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00008202 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8203 FT->getReturnType()->isAnyPointerType() ||
8204 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00008205 // DllMain is exempt because a return value of zero means it failed.
8206 if (FD->getName() != "DllMain")
8207 FD->setHasImplicitReturnZero(true);
8208
8209 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00008210 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00008211 FD->setInvalidDecl();
8212 }
John McCalld9baf6a2009-07-24 03:03:21 +00008213}
8214
Eli Friedmand5a55bd2008-05-20 13:48:25 +00008215bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008216 // FIXME: Need strict checking. In C89, we need to check for
8217 // any assignment, increment, decrement, function-calls, or
8218 // commas outside of a sizeof. In C99, it's the same list,
8219 // except that the aforementioned are allowed in unevaluated
8220 // expressions. Everything else falls under the
8221 // "may accept other forms of constant expressions" exception.
8222 // (We never end up here for C++, so the constant expression
8223 // rules there don't matter.)
Abramo Bagnara847c6602014-05-22 19:20:46 +00008224 const Expr *Culprit;
8225 if (Init->isConstantInitializer(Context, false, &Culprit))
Eli Friedman7bfab362009-02-22 06:45:27 +00008226 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00008227 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8228 << Culprit->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00008229 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00008230}
8231
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008232namespace {
8233 // Visits an initialization expression to see if OrigDecl is evaluated in
8234 // its own initialization and throws a warning if it does.
8235 class SelfReferenceChecker
8236 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8237 Sema &S;
8238 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00008239 bool isRecordType;
8240 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00008241 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008242
Richard Trieue396ba62014-09-23 22:52:42 +00008243 bool isInitList;
8244 llvm::SmallVector<unsigned, 4> InitFieldIndex;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008245 public:
8246 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8247
8248 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00008249 S(S), OrigDecl(OrigDecl) {
8250 isPODType = false;
8251 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00008252 isReferenceType = false;
Richard Trieue396ba62014-09-23 22:52:42 +00008253 isInitList = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00008254 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8255 isPODType = VD->getType().isPODType(S.Context);
8256 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00008257 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00008258 }
8259 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008260
Richard Trieue396ba62014-09-23 22:52:42 +00008261 // For most expressions, just call the visitor. For initializer lists,
8262 // track the index of the field being initialized since fields are
8263 // initialized in order allowing use of previously initialized fields.
8264 void CheckExpr(Expr *E) {
8265 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8266 if (!InitList) {
8267 Visit(E);
8268 return;
8269 }
8270
8271 // Track and increment the index here.
8272 isInitList = true;
8273 InitFieldIndex.push_back(0);
8274 for (auto Child : InitList->children()) {
8275 CheckExpr(cast<Expr>(Child));
8276 ++InitFieldIndex.back();
8277 }
8278 InitFieldIndex.pop_back();
8279 }
8280
8281 // Returns true if MemberExpr is checked and no futher checking is needed.
8282 // Returns false if additional checking is required.
8283 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8284 llvm::SmallVector<FieldDecl*, 4> Fields;
8285 Expr *Base = E;
8286 bool ReferenceField = false;
8287
8288 // Get the field memebers used.
8289 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8290 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8291 if (!FD)
8292 return false;
8293 Fields.push_back(FD);
8294 if (FD->getType()->isReferenceType())
8295 ReferenceField = true;
8296 Base = ME->getBase()->IgnoreParenImpCasts();
8297 }
8298
8299 // Keep checking only if the base Decl is the same.
8300 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8301 if (!DRE || DRE->getDecl() != OrigDecl)
8302 return false;
8303
8304 // A reference field can be bound to an unininitialized field.
8305 if (CheckReference && !ReferenceField)
8306 return true;
8307
8308 // Convert FieldDecls to their index number.
8309 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8310 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8311 UsedFieldIndex.push_back((*I)->getFieldIndex());
8312 }
8313
8314 // See if a warning is needed by checking the first difference in index
8315 // numbers. If field being used has index less than the field being
8316 // initialized, then the use is safe.
8317 for (auto UsedIter = UsedFieldIndex.begin(),
8318 UsedEnd = UsedFieldIndex.end(),
8319 OrigIter = InitFieldIndex.begin(),
8320 OrigEnd = InitFieldIndex.end();
8321 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8322 if (*UsedIter < *OrigIter)
8323 return true;
8324 if (*UsedIter > *OrigIter)
8325 break;
8326 }
8327
8328 // TODO: Add a different warning which will print the field names.
8329 HandleDeclRefExpr(DRE);
8330 return true;
8331 }
8332
Richard Trieu64c51ab2012-05-09 00:21:34 +00008333 // For most expressions, the cast is directly above the DeclRefExpr.
8334 // For conditional operators, the cast can be outside the conditional
8335 // operator if both expressions are DeclRefExpr's.
8336 void HandleValue(Expr *E) {
Richard Trieuabf6ec42014-08-27 22:15:10 +00008337 E = E->IgnoreParens();
Richard Trieu64c51ab2012-05-09 00:21:34 +00008338 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8339 HandleDeclRefExpr(DRE);
8340 return;
8341 }
8342
8343 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8344 HandleValue(CO->getTrueExpr());
8345 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00008346 return;
8347 }
8348
Richard Trieuabf6ec42014-08-27 22:15:10 +00008349 if (BinaryConditionalOperator *BCO =
8350 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2a07c962014-09-04 23:19:34 +00008351 Visit(BCO->getCond());
Richard Trieuabf6ec42014-08-27 22:15:10 +00008352 HandleValue(BCO->getFalseExpr());
8353 return;
8354 }
8355
8356 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8357 HandleValue(OVE->getSourceExpr());
8358 return;
8359 }
8360
8361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Trieu78dd7252014-09-24 03:53:56 +00008362 if (BO->getOpcode() == BO_Comma) {
8363 Visit(BO->getLHS());
Richard Trieuabf6ec42014-08-27 22:15:10 +00008364 HandleValue(BO->getRHS());
Richard Trieu78dd7252014-09-24 03:53:56 +00008365 return;
8366 }
Richard Trieuabf6ec42014-08-27 22:15:10 +00008367 }
8368
Richard Trieu742c6ed2012-10-03 00:41:36 +00008369 if (isa<MemberExpr>(E)) {
Richard Trieue396ba62014-09-23 22:52:42 +00008370 if (isInitList) {
8371 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8372 false /*CheckReference*/))
8373 return;
8374 }
8375
Richard Trieu742c6ed2012-10-03 00:41:36 +00008376 Expr *Base = E->IgnoreParenImpCasts();
8377 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8378 // Check for static member variables and don't warn on them.
8379 if (!isa<FieldDecl>(ME->getMemberDecl()))
8380 return;
8381 Base = ME->getBase()->IgnoreParenImpCasts();
8382 }
8383 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8384 HandleDeclRefExpr(DRE);
8385 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008386 }
Richard Trieu2a07c962014-09-04 23:19:34 +00008387
8388 Visit(E);
Richard Trieu64c51ab2012-05-09 00:21:34 +00008389 }
8390
Richard Trieu2a07c962014-09-04 23:19:34 +00008391 // Reference types not handled in HandleValue are handled here since all
8392 // uses of references are bad, not just r-value uses.
Richard Trieu32673472012-10-01 17:39:51 +00008393 void VisitDeclRefExpr(DeclRefExpr *E) {
8394 if (isReferenceType)
8395 HandleDeclRefExpr(E);
8396 }
8397
Richard Trieu64c51ab2012-05-09 00:21:34 +00008398 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00008399 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu2a07c962014-09-04 23:19:34 +00008400 (isRecordType && E->getCastKind() == CK_NoOp)) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00008401 HandleValue(E->getSubExpr());
Richard Trieu2a07c962014-09-04 23:19:34 +00008402 return;
8403 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008404
8405 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008406 }
8407
Richard Trieua04ad1a2011-09-01 21:44:13 +00008408 void VisitMemberExpr(MemberExpr *E) {
Richard Trieue396ba62014-09-23 22:52:42 +00008409 if (isInitList) {
8410 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8411 return;
8412 }
8413
Richard Trieu64c51ab2012-05-09 00:21:34 +00008414 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00008415 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008416
Richard Trieu742c6ed2012-10-03 00:41:36 +00008417 // Warn when a non-static method call is followed by non-static member
8418 // field accesses, which is followed by a DeclRefExpr.
8419 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8420 bool Warn = (MD && !MD->isStatic());
8421 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8422 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8423 if (!isa<FieldDecl>(ME->getMemberDecl()))
8424 Warn = false;
8425 Base = ME->getBase()->IgnoreParenImpCasts();
8426 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008427
Richard Trieu742c6ed2012-10-03 00:41:36 +00008428 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8429 if (Warn)
8430 HandleDeclRefExpr(DRE);
8431 return;
8432 }
8433
8434 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8435 // Visit that expression.
8436 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008437 }
8438
Richard Trieu8fbd91d2013-03-26 03:41:40 +00008439 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8440 if (E->getNumArgs() > 0)
8441 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8442 HandleDeclRefExpr(DRE);
8443
8444 Inherited::VisitCXXOperatorCallExpr(E);
8445 }
8446
Richard Trieua04ad1a2011-09-01 21:44:13 +00008447 void VisitUnaryOperator(UnaryOperator *E) {
8448 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00008449 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8450 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8451 if (!isPODType)
8452 HandleValue(E->getSubExpr());
8453 return;
8454 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008455 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00008456 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008457
8458 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8459
Richard Trieu4834ad22014-08-12 21:05:04 +00008460 void VisitCXXConstructExpr(CXXConstructExpr *E) {
8461 if (E->getConstructor()->isCopyConstructor()) {
8462 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) {
8463 HandleDeclRefExpr(DRE);
8464 }
8465 }
8466 Inherited::VisitCXXConstructExpr(E);
8467 }
8468
Richard Trieu11fd0792014-08-26 04:30:55 +00008469 void VisitCallExpr(CallExpr *E) {
8470 // Treat std::move as a use.
8471 if (E->getNumArgs() == 1) {
8472 if (FunctionDecl *FD = E->getDirectCallee()) {
8473 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
Richard Trieuabf6ec42014-08-27 22:15:10 +00008474 HandleValue(E->getArg(0));
Richard Trieu2a07c962014-09-04 23:19:34 +00008475 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00008476 }
8477 }
8478 }
8479
8480 Inherited::VisitCallExpr(E);
8481 }
8482
Richard Trieu2a07c962014-09-04 23:19:34 +00008483 // A custom visitor for BinaryConditionalOperator is needed because the
8484 // regular visitor would check the condition and true expression separately
8485 // but both point to the same place giving duplicate diagnostics.
8486 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8487 Visit(E->getCond());
8488 Visit(E->getFalseExpr());
8489 }
8490
Richard Trieua04ad1a2011-09-01 21:44:13 +00008491 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00008492 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008493 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00008494 unsigned diag;
8495 if (isReferenceType) {
8496 diag = diag::warn_uninit_self_reference_in_reference_init;
8497 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8498 diag = diag::warn_static_self_reference_in_init;
8499 } else {
8500 diag = diag::warn_uninit_self_reference_in_init;
8501 }
8502
Richard Trieua04ad1a2011-09-01 21:44:13 +00008503 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00008504 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00008505 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008506 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00008507 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008508 }
8509 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008510
Richard Trieu32673472012-10-01 17:39:51 +00008511 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8512 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8513 bool DirectInit) {
8514 // Parameters arguments are occassionially constructed with itself,
8515 // for instance, in recursive functions. Skip them.
8516 if (isa<ParmVarDecl>(OrigDecl))
8517 return;
8518
8519 E = E->IgnoreParens();
8520
8521 // Skip checking T a = a where T is not a record or reference type.
8522 // Doing so is a way to silence uninitialized warnings.
8523 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8524 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8525 if (ICE->getCastKind() == CK_LValueToRValue)
8526 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8527 if (DRE->getDecl() == OrigDecl)
8528 return;
8529
Richard Trieue396ba62014-09-23 22:52:42 +00008530 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
Richard Trieu32673472012-10-01 17:39:51 +00008531 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008532}
8533
Douglas Gregor5fb53972009-01-14 15:45:31 +00008534/// AddInitializerToDecl - Adds the initializer Init to the
8535/// declaration dcl. If DirectInit is true, this is C++ direct
8536/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008537void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8538 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008539 // If there is no declaration, there was an error parsing it. Just ignore
8540 // the initializer.
Craig Topperc3ec1492014-05-26 06:22:03 +00008541 if (!RealDecl || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008542 return;
Mike Stump11289f42009-09-09 15:08:12 +00008543
Douglas Gregor0c880302009-03-11 23:00:04 +00008544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8545 // With declarators parsed the way they are, the parser cannot
8546 // distinguish between a normal initializer and a pure-specifier.
8547 // Thus this grotesque test.
8548 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008549 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008550 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8551 CheckPureMethod(Method, Init->getSourceRange());
8552 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008553 Diag(Method->getLocation(), diag::err_member_function_initialization)
8554 << Method->getDeclName() << Init->getSourceRange();
8555 Method->setInvalidDecl();
8556 }
8557 return;
8558 }
8559
Steve Naroff437b4d82007-09-12 20:13:48 +00008560 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8561 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008562 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8563 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008564 RealDecl->setInvalidDecl();
8565 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008566 }
Sebastian Redla9351792012-02-11 23:51:47 +00008567 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8568
Richard Smith0cc85782011-12-15 19:20:59 +00008569 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008570 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008571 Expr *DeduceInit = Init;
8572 // Initializer could be a C++ direct-initializer. Deduction only works if it
8573 // contains exactly one expression.
8574 if (CXXDirectInit) {
8575 if (CXXDirectInit->getNumExprs() == 0) {
8576 // It isn't possible to write this directly, but it is possible to
8577 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008578 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008579 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8580 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008581 << VDecl->getDeclName() << VDecl->getType()
8582 << VDecl->getSourceRange();
8583 RealDecl->setInvalidDecl();
8584 return;
8585 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008586 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008587 VDecl->isInitCapture()
8588 ? diag::err_init_capture_multiple_expressions
8589 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008590 << VDecl->getDeclName() << VDecl->getType()
8591 << VDecl->getSourceRange();
8592 RealDecl->setInvalidDecl();
8593 return;
8594 } else {
8595 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008596 if (isa<InitListExpr>(DeduceInit))
8597 Diag(CXXDirectInit->getLocStart(),
8598 diag::err_auto_var_init_paren_braces)
8599 << VDecl->getDeclName() << VDecl->getType()
8600 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008601 }
8602 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008603
8604 // Expressions default to 'id' when we're in a debugger.
8605 bool DefaultedToAuto = false;
8606 if (getLangOpts().DebuggerCastResultToId &&
8607 Init->getType() == Context.UnknownAnyTy) {
8608 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8609 if (Result.isInvalid()) {
8610 VDecl->setInvalidDecl();
8611 return;
8612 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008613 Init = Result.get();
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008614 DefaultedToAuto = true;
8615 }
Richard Smith061f1e22013-04-30 21:23:01 +00008616
8617 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008618 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008619 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008620 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008621 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008622 RealDecl->setInvalidDecl();
8623 return;
8624 }
Richard Smith061f1e22013-04-30 21:23:01 +00008625 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008626 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008627
John McCall31168b02011-06-15 23:02:42 +00008628 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008629 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008630 VDecl->setInvalidDecl();
8631
Jordan Rosed8d56692012-06-08 22:46:07 +00008632 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8633 // 'id' instead of a specific object type prevents most of our usual checks.
8634 // We only want to warn outside of template instantiations, though:
8635 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008636 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008637 DeducedType->isObjCIdType()) {
8638 SourceLocation Loc =
8639 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008640 Diag(Loc, diag::warn_auto_var_is_id)
8641 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8642 }
8643
Richard Smith30482bc2011-02-20 03:19:35 +00008644 // If this is a redeclaration, check that the type we just deduced matches
8645 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008646 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8647 // We never need to merge the type, because we cannot form an incomplete
8648 // array of auto, nor deduce such a type.
8649 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8650 }
Richard Smith27d807c2013-04-30 13:56:41 +00008651
8652 // Check the deduced type is valid for a variable declaration.
8653 CheckVariableDeclarationType(VDecl);
8654 if (VDecl->isInvalidDecl())
8655 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008656 }
Richard Smith0cc85782011-12-15 19:20:59 +00008657
Nico Rieck8e9791f2014-02-26 21:27:13 +00008658 // dllimport cannot be used on variable definitions.
8659 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8660 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8661 VDecl->setInvalidDecl();
8662 return;
8663 }
8664
Richard Smith0cc85782011-12-15 19:20:59 +00008665 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8666 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8667 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8668 VDecl->setInvalidDecl();
8669 return;
8670 }
8671
Sebastian Redla9351792012-02-11 23:51:47 +00008672 if (!VDecl->getType()->isDependentType()) {
8673 // A definition must end up with a complete type, which means it must be
8674 // complete with the restriction that an array type might be completed by
8675 // the initializer; note that later code assumes this restriction.
8676 QualType BaseDeclType = VDecl->getType();
8677 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8678 BaseDeclType = Array->getElementType();
8679 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8680 diag::err_typecheck_decl_incomplete_type)) {
8681 RealDecl->setInvalidDecl();
8682 return;
8683 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008684
Sebastian Redla9351792012-02-11 23:51:47 +00008685 // The variable can not have an abstract class type.
8686 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8687 diag::err_abstract_type_in_decl,
8688 AbstractVariableType))
8689 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008690 }
8691
Sebastian Redl5ca79842010-02-01 20:16:42 +00008692 const VarDecl *Def;
8693 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008694 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008695 << VDecl->getDeclName();
8696 Diag(Def->getLocation(), diag::note_previous_definition);
8697 VDecl->setInvalidDecl();
8698 return;
8699 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008700
8701 const VarDecl *PrevInit = nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008702 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008703 // C++ [class.static.data]p4
8704 // If a static data member is of const integral or const
8705 // enumeration type, its declaration in the class definition can
8706 // specify a constant-initializer which shall be an integral
8707 // constant expression (5.19). In that case, the member can appear
8708 // in integral constant expressions. The member shall still be
8709 // defined in a namespace scope if it is used in the program and the
8710 // namespace scope definition shall not contain an initializer.
8711 //
8712 // We already performed a redefinition check above, but for static
8713 // data members we also need to check whether there was an in-class
8714 // declaration with an initializer.
8715 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008716 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8717 << VDecl->getDeclName();
8718 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008719 return;
8720 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008721
Douglas Gregor71f39c92010-12-16 01:31:22 +00008722 if (VDecl->hasLocalStorage())
8723 getCurFunction()->setHasBranchProtectedScope();
8724
8725 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8726 VDecl->setInvalidDecl();
8727 return;
8728 }
8729 }
John McCalld4e1b762010-08-01 01:24:59 +00008730
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008731 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8732 // a kernel function cannot be initialized."
8733 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8734 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8735 VDecl->setInvalidDecl();
8736 return;
8737 }
8738
Steve Naroff61091402007-09-12 14:07:44 +00008739 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008740 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008741 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008742
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008743 // Expressions default to 'id' when we're in a debugger
8744 // and we are assigning it to a variable of Objective-C pointer type.
8745 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8746 Init->getType() == Context.UnknownAnyTy) {
8747 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8748 if (Result.isInvalid()) {
8749 VDecl->setInvalidDecl();
8750 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008751 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008752 Init = Result.get();
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008753 }
Richard Smith0cc85782011-12-15 19:20:59 +00008754
8755 // Perform the initialization.
8756 if (!VDecl->isInvalidDecl()) {
8757 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8758 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008759 = DirectInit ?
8760 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8761 Init->getLocStart(),
8762 Init->getLocEnd())
8763 : InitializationKind::CreateDirectList(
8764 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008765 : InitializationKind::CreateCopy(VDecl->getLocation(),
8766 Init->getLocStart());
8767
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008768 MultiExprArg Args = Init;
8769 if (CXXDirectInit)
8770 Args = MultiExprArg(CXXDirectInit->getExprs(),
8771 CXXDirectInit->getNumExprs());
8772
8773 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8774 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008775 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008776 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008777 return;
Steve Naroff61091402007-09-12 14:07:44 +00008778 }
Richard Smith0cc85782011-12-15 19:20:59 +00008779
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008780 Init = Result.getAs<Expr>();
Richard Smith0cc85782011-12-15 19:20:59 +00008781 }
8782
Richard Trieu32673472012-10-01 17:39:51 +00008783 // Check for self-references within variable initializers.
8784 // Variables declared within a function/method body (except for references)
8785 // are handled by a dataflow analysis.
8786 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8787 VDecl->getType()->isReferenceType()) {
8788 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8789 }
8790
Richard Smith0cc85782011-12-15 19:20:59 +00008791 // If the type changed, it means we had an incomplete type that was
8792 // completed by the initializer. For example:
8793 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008794 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008795 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008796 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008797
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008798 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008799 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8800
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008801 if (VDecl->hasAttr<BlocksAttr>())
8802 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008803
8804 // It is safe to assign a weak reference into a strong variable.
8805 // Although this code can still have problems:
8806 // id x = self.weakProp;
8807 // id y = self.weakProp;
8808 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8809 // paths through the function. This should be revisited if
8810 // -Wrepeated-use-of-weak is made flow-sensitive.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008811 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8812 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8813 Init->getLocStart()))
Jordan Rosed3934582012-09-28 22:21:30 +00008814 getCurFunction()->markSafeWeakUse(Init);
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008815 }
8816
Richard Smith945f8d32013-01-14 22:39:08 +00008817 // The initialization is usually a full-expression.
8818 //
8819 // FIXME: If this is a braced initialization of an aggregate, it is not
8820 // an expression, and each individual field initializer is a separate
8821 // full-expression. For instance, in:
8822 //
8823 // struct Temp { ~Temp(); };
8824 // struct S { S(Temp); };
8825 // struct T { S a, b; } t = { Temp(), Temp() }
8826 //
8827 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008828 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8829 false,
8830 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008831 if (Result.isInvalid()) {
8832 VDecl->setInvalidDecl();
8833 return;
8834 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008835 Init = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00008836
Richard Smith0cc85782011-12-15 19:20:59 +00008837 // Attach the initializer to the decl.
8838 VDecl->setInit(Init);
8839
8840 if (VDecl->isLocalVarDecl()) {
8841 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8842 // static storage duration shall be constant expressions or string literals.
8843 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008844 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00008845 const Expr *Culprit;
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008846 if (VDecl->getStorageClass() == SC_Static)
8847 CheckForConstantInitializer(Init, DclT);
8848 // C89 is stricter than C99 for non-static aggregate types.
8849 // C89 6.5.7p3: All the expressions [...] in an initializer list
8850 // for an object that has aggregate or union type shall be
8851 // constant expressions.
8852 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008853 isa<InitListExpr>(Init) &&
Abramo Bagnara847c6602014-05-22 19:20:46 +00008854 !Init->isConstantInitializer(Context, false, &Culprit))
8855 Diag(Culprit->getExprLoc(),
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008856 diag::ext_aggregate_init_not_constant)
Abramo Bagnara847c6602014-05-22 19:20:46 +00008857 << Culprit->getSourceRange();
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008858 }
Mike Stump11289f42009-09-09 15:08:12 +00008859 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008860 VDecl->getLexicalDeclContext()->isRecord()) {
8861 // This is an in-class initialization for a static data member, e.g.,
8862 //
8863 // struct S {
8864 // static const int value = 17;
8865 // };
8866
Douglas Gregor0c880302009-03-11 23:00:04 +00008867 // C++ [class.mem]p4:
8868 // A member-declarator can contain a constant-initializer only
8869 // if it declares a static member (9.4) of const integral or
8870 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008871 //
Richard Smith0cc85782011-12-15 19:20:59 +00008872 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008873 // If a non-volatile const static data member is of integral or
8874 // enumeration type, its declaration in the class definition can
8875 // specify a brace-or-equal-initializer in which every initalizer-clause
8876 // that is an assignment-expression is a constant expression. A static
8877 // data member of literal type can be declared in the class definition
8878 // with the constexpr specifier; if so, its declaration shall specify a
8879 // brace-or-equal-initializer in which every initializer-clause that is
8880 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008881
8882 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008883 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008884
Richard Smith2316cd82011-09-29 19:11:37 +00008885 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008886 // type. We separately check that every constexpr variable is of literal
8887 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008888 } else if (VDecl->isConstexpr()) {
8889
John McCalldb768922010-09-10 23:21:22 +00008890 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008891 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008892 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8893 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008894 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008895
8896 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008897 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008898 // Check whether the expression is a constant expression.
8899 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008900 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008901 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008902 // in-class initializer cannot be volatile.
8903 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8904 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008905 ; // Nothing to check.
8906 else if (Init->isIntegerConstantExpr(Context, &Loc))
8907 ; // Ok, it's an ICE!
8908 else if (Init->isEvaluatable(Context)) {
8909 // If we can constant fold the initializer through heroics, accept it,
8910 // but report this as a use of an extension for -pedantic.
8911 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8912 << Init->getSourceRange();
8913 } else {
8914 // Otherwise, this is some crazy unknown case. Report the issue at the
8915 // location provided by the isIntegerConstantExpr failed check.
8916 Diag(Loc, diag::err_in_class_initializer_non_constant)
8917 << Init->getSourceRange();
8918 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008919 }
8920
Richard Smith0cc85782011-12-15 19:20:59 +00008921 // We allow foldable floating-point constants as an extension.
8922 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008923 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8924 // it anyway and provide a fixit to add the 'constexpr'.
8925 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008926 Diag(VDecl->getLocation(),
8927 diag::ext_in_class_initializer_float_type_cxx11)
8928 << DclT << Init->getSourceRange();
8929 Diag(VDecl->getLocStart(),
8930 diag::note_in_class_initializer_float_type_cxx11)
8931 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008932 } else {
8933 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8934 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008935
Richard Smithcf656382013-01-25 04:22:16 +00008936 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8937 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8938 << Init->getSourceRange();
8939 VDecl->setInvalidDecl();
8940 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008941 }
Richard Smith256336d2011-09-29 23:18:34 +00008942
Richard Smith0cc85782011-12-15 19:20:59 +00008943 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008944 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008945 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008946 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008947 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8948 VDecl->setConstexpr(true);
8949
Richard Smith2316cd82011-09-29 19:11:37 +00008950 } else {
8951 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008952 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008953 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008954 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008955 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008956 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008957 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008958 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008959 VDecl->isExternC())) &&
8960 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008961 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008962
Richard Smith0cc85782011-12-15 19:20:59 +00008963 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008964 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008965 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00008966 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008967
Sebastian Redla9351792012-02-11 23:51:47 +00008968 // We will represent direct-initialization similarly to copy-initialization:
8969 // int x(1); -as-> int x = 1;
8970 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8971 //
8972 // Clients that want to distinguish between the two forms, can check for
8973 // direct initializer using VarDecl::getInitStyle().
8974 // A major benefit is that clients that don't particularly care about which
8975 // exactly form was it (like the CodeGen) can handle both cases without
8976 // special case code.
8977
8978 // C++ 8.5p11:
8979 // The form of initialization (using parentheses or '=') is generally
8980 // insignificant, but does matter when the entity being initialized has a
8981 // class type.
8982 if (CXXDirectInit) {
8983 assert(DirectInit && "Call-style initializer must be direct init.");
8984 VDecl->setInitStyle(VarDecl::CallInit);
8985 } else if (DirectInit) {
8986 // This must be list-initialization. No other way is direct-initialization.
8987 VDecl->setInitStyle(VarDecl::ListInit);
8988 }
8989
John McCall8b7fd8f12011-01-19 11:48:09 +00008990 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008991}
8992
John McCalleae5acb2010-03-31 02:13:20 +00008993/// ActOnInitializerError - Given that there was an error parsing an
8994/// initializer for the given declaration, try to return to some form
8995/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008996void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008997 // Our main concern here is re-establishing invariants like "a
8998 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008999 if (!D || D->isInvalidDecl()) return;
9000
9001 VarDecl *VD = dyn_cast<VarDecl>(D);
9002 if (!VD) return;
9003
Richard Smith30482bc2011-02-20 03:19:35 +00009004 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00009005 if (ParsingInitForAutoVars.count(D)) {
9006 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009007 return;
9008 }
9009
John McCalleae5acb2010-03-31 02:13:20 +00009010 QualType Ty = VD->getType();
9011 if (Ty->isDependentType()) return;
9012
9013 // Require a complete type.
9014 if (RequireCompleteType(VD->getLocation(),
9015 Context.getBaseElementType(Ty),
9016 diag::err_typecheck_decl_incomplete_type)) {
9017 VD->setInvalidDecl();
9018 return;
9019 }
9020
Alp Toker48c7e172014-04-15 16:24:50 +00009021 // Require a non-abstract type.
John McCalleae5acb2010-03-31 02:13:20 +00009022 if (RequireNonAbstractType(VD->getLocation(), Ty,
9023 diag::err_abstract_type_in_decl,
9024 AbstractVariableType)) {
9025 VD->setInvalidDecl();
9026 return;
9027 }
9028
9029 // Don't bother complaining about constructors or destructors,
9030 // though.
9031}
9032
John McCall48871652010-08-21 09:40:31 +00009033void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00009034 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00009035 // If there is no declaration, there was an error parsing it. Just ignore it.
Craig Topperc3ec1492014-05-26 06:22:03 +00009036 if (!RealDecl)
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00009037 return;
9038
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009039 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9040 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00009041
Richard Smithf0215fe2011-12-25 21:17:58 +00009042 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00009043 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00009044 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9045 << Var->getDeclName() << Type;
9046 Var->setInvalidDecl();
9047 return;
9048 }
Mike Stump11289f42009-09-09 15:08:12 +00009049
Richard Smithf0215fe2011-12-25 21:17:58 +00009050 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00009051 // the constexpr specifier; if so, its declaration shall specify
9052 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00009053 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9054 // the definition of a variable [...] or the declaration of a static data
9055 // member.
9056 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9057 if (Var->isStaticDataMember())
9058 Diag(Var->getLocation(),
9059 diag::err_constexpr_static_mem_var_requires_init)
9060 << Var->getDeclName();
9061 else
9062 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00009063 Var->setInvalidDecl();
9064 return;
9065 }
9066
Joey Gouly96b94e62014-01-03 14:16:55 +00009067 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9068 // be initialized.
9069 if (!Var->isInvalidDecl() &&
9070 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00009071 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00009072 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9073 Var->setInvalidDecl();
9074 return;
9075 }
9076
Douglas Gregore6565622010-02-09 07:26:29 +00009077 switch (Var->isThisDeclarationADefinition()) {
9078 case VarDecl::Definition:
9079 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9080 break;
9081
9082 // We have an out-of-line definition of a static data member
9083 // that has an in-class initializer, so we type-check this like
9084 // a declaration.
9085 //
9086 // Fall through
9087
9088 case VarDecl::DeclarationOnly:
9089 // It's only a declaration.
9090
9091 // Block scope. C99 6.7p7: If an identifier for an object is
9092 // declared with no linkage (C99 6.2.2p6), the type for the
9093 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00009094 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00009095 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00009096 RequireCompleteType(Var->getLocation(), Type,
9097 diag::err_typecheck_decl_incomplete_type))
9098 Var->setInvalidDecl();
9099
9100 // Make sure that the type is not abstract.
9101 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9102 RequireNonAbstractType(Var->getLocation(), Type,
9103 diag::err_abstract_type_in_decl,
9104 AbstractVariableType))
9105 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00009106 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00009107 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00009108 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00009109 Diag(Var->getLocation(), diag::note_private_extern);
9110 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00009111
Douglas Gregore6565622010-02-09 07:26:29 +00009112 return;
9113
9114 case VarDecl::TentativeDefinition:
9115 // File scope. C99 6.9.2p2: A declaration of an identifier for an
9116 // object that has file scope without an initializer, and without a
9117 // storage-class specifier or with the storage-class specifier "static",
9118 // constitutes a tentative definition. Note: A tentative definition with
9119 // external linkage is valid (C99 6.2.2p5).
9120 if (!Var->isInvalidDecl()) {
9121 if (const IncompleteArrayType *ArrayT
9122 = Context.getAsIncompleteArrayType(Type)) {
9123 if (RequireCompleteType(Var->getLocation(),
9124 ArrayT->getElementType(),
9125 diag::err_illegal_decl_array_incomplete_type))
9126 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00009127 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00009128 // C99 6.9.2p3: If the declaration of an identifier for an object is
9129 // a tentative definition and has internal linkage (C99 6.2.2p3), the
9130 // declared type shall not be an incomplete type.
9131 // NOTE: code such as the following
9132 // static struct s;
9133 // struct s { int a; };
9134 // is accepted by gcc. Hence here we issue a warning instead of
9135 // an error and we do not invalidate the static declaration.
9136 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009137 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00009138 RequireCompleteType(Var->getLocation(), Type,
9139 diag::ext_typecheck_decl_incomplete_type);
9140 }
9141 }
9142
9143 // Record the tentative definition; we're done.
9144 if (!Var->isInvalidDecl())
9145 TentativeDefinitions.push_back(Var);
9146 return;
9147 }
9148
9149 // Provide a specific diagnostic for uninitialized variable
9150 // definitions with incomplete array type.
9151 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00009152 Diag(Var->getLocation(),
9153 diag::err_typecheck_incomplete_array_needs_initializer);
9154 Var->setInvalidDecl();
9155 return;
9156 }
9157
John McCalla755f0f2010-08-01 01:25:24 +00009158 // Provide a specific diagnostic for uninitialized variable
9159 // definitions with reference type.
9160 if (Type->isReferenceType()) {
9161 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9162 << Var->getDeclName()
9163 << SourceRange(Var->getLocation(), Var->getLocation());
9164 Var->setInvalidDecl();
9165 return;
9166 }
Douglas Gregore6565622010-02-09 07:26:29 +00009167
9168 // Do not attempt to type-check the default initializer for a
9169 // variable with dependent type.
9170 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00009171 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009172
Douglas Gregore6565622010-02-09 07:26:29 +00009173 if (Var->isInvalidDecl())
9174 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00009175
David Majnemer837d5de2014-07-09 17:15:52 +00009176 if (!Var->hasAttr<AliasAttr>()) {
9177 if (RequireCompleteType(Var->getLocation(),
9178 Context.getBaseElementType(Type),
9179 diag::err_typecheck_decl_incomplete_type)) {
9180 Var->setInvalidDecl();
9181 return;
9182 }
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009183 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009184
Douglas Gregore6565622010-02-09 07:26:29 +00009185 // The variable can not have an abstract class type.
9186 if (RequireNonAbstractType(Var->getLocation(), Type,
9187 diag::err_abstract_type_in_decl,
9188 AbstractVariableType)) {
9189 Var->setInvalidDecl();
9190 return;
9191 }
9192
Douglas Gregor9574af62011-05-21 17:52:48 +00009193 // Check for jumps past the implicit initializer. C++0x
9194 // clarifies that this applies to a "variable with automatic
9195 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00009196 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00009197 // A program that jumps from a point where a variable with automatic
9198 // storage duration is not in scope to a point where it is in scope is
9199 // ill-formed unless the variable has scalar type, class type with a
9200 // trivial default constructor and a trivial destructor, a cv-qualified
9201 // version of one of these types, or an array of one of the preceding
9202 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009203 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00009204 if (const RecordType *Record
9205 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00009206 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00009207 // Mark the function for further checking even if the looser rules of
9208 // C++11 do not require such checks, so that we can diagnose
9209 // incompatibilities with C++98.
9210 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00009211 getCurFunction()->setHasBranchProtectedScope();
9212 }
Douglas Gregore6565622010-02-09 07:26:29 +00009213 }
Douglas Gregor9574af62011-05-21 17:52:48 +00009214
9215 // C++03 [dcl.init]p9:
9216 // If no initializer is specified for an object, and the
9217 // object is of (possibly cv-qualified) non-POD class type (or
9218 // array thereof), the object shall be default-initialized; if
9219 // the object is of const-qualified type, the underlying class
9220 // type shall have a user-declared default
9221 // constructor. Otherwise, if no initializer is specified for
9222 // a non- static object, the object and its subobjects, if
9223 // any, have an indeterminate initial value); if the object
9224 // or any of its subobjects are of const-qualified type, the
9225 // program is ill-formed.
9226 // C++0x [dcl.init]p11:
9227 // If no initializer is specified for an object, the object is
9228 // default-initialized; [...].
9229 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9230 InitializationKind Kind
9231 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00009232
9233 InitializationSequence InitSeq(*this, Entity, Kind, None);
9234 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00009235 if (Init.isInvalid())
9236 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00009237 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00009238 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00009239 // This is important for template substitution.
9240 Var->setInitStyle(VarDecl::CallInit);
9241 }
Douglas Gregor589973b2010-03-08 02:45:10 +00009242
John McCall8b7fd8f12011-01-19 11:48:09 +00009243 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009244 }
9245}
9246
Richard Smith02e85f32011-04-14 22:09:26 +00009247void Sema::ActOnCXXForRangeDecl(Decl *D) {
9248 VarDecl *VD = dyn_cast<VarDecl>(D);
9249 if (!VD) {
9250 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9251 D->setInvalidDecl();
9252 return;
9253 }
9254
9255 VD->setCXXForRangeDecl(true);
9256
9257 // for-range-declaration cannot be given a storage class specifier.
9258 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009259 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00009260 case SC_None:
9261 break;
9262 case SC_Extern:
9263 Error = 0;
9264 break;
9265 case SC_Static:
9266 Error = 1;
9267 break;
9268 case SC_PrivateExtern:
9269 Error = 2;
9270 break;
9271 case SC_Auto:
9272 Error = 3;
9273 break;
9274 case SC_Register:
9275 Error = 4;
9276 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00009277 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00009278 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00009279 }
Richard Smith2316cd82011-09-29 19:11:37 +00009280 if (VD->isConstexpr())
9281 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00009282 if (Error != -1) {
9283 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9284 << VD->getDeclName() << Error;
9285 D->setInvalidDecl();
9286 }
9287}
9288
Richard Smith955bf012014-06-19 11:42:00 +00009289StmtResult
9290Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9291 IdentifierInfo *Ident,
9292 ParsedAttributes &Attrs,
9293 SourceLocation AttrEnd) {
9294 // C++1y [stmt.iter]p1:
9295 // A range-based for statement of the form
9296 // for ( for-range-identifier : for-range-initializer ) statement
9297 // is equivalent to
9298 // for ( auto&& for-range-identifier : for-range-initializer ) statement
9299 DeclSpec DS(Attrs.getPool().getFactory());
9300
9301 const char *PrevSpec;
9302 unsigned DiagID;
9303 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9304 getPrintingPolicy());
9305
9306 Declarator D(DS, Declarator::ForContext);
9307 D.SetIdentifier(Ident, IdentLoc);
9308 D.takeAttributes(Attrs, AttrEnd);
9309
9310 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9311 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9312 EmptyAttrs, IdentLoc);
9313 Decl *Var = ActOnDeclarator(S, D);
9314 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9315 FinalizeDeclaration(Var);
9316 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9317 AttrEnd.isValid() ? AttrEnd : IdentLoc);
9318}
9319
John McCall8b7fd8f12011-01-19 11:48:09 +00009320void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9321 if (var->isInvalidDecl()) return;
9322
John McCall31168b02011-06-15 23:02:42 +00009323 // In ARC, don't allow jumps past the implicit initialization of a
9324 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009325 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009326 var->hasLocalStorage()) {
9327 switch (var->getType().getObjCLifetime()) {
9328 case Qualifiers::OCL_None:
9329 case Qualifiers::OCL_ExplicitNone:
9330 case Qualifiers::OCL_Autoreleasing:
9331 break;
9332
9333 case Qualifiers::OCL_Weak:
9334 case Qualifiers::OCL_Strong:
9335 getCurFunction()->setHasBranchProtectedScope();
9336 break;
9337 }
9338 }
9339
John McCall8a4e2e42014-01-29 08:33:09 +00009340 // Warn about externally-visible variables being defined without a
9341 // prior declaration. We only want to do this for global
9342 // declarations, but we also specifically need to avoid doing it for
9343 // class members because the linkage of an anonymous class can
9344 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00009345 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00009346 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00009347 var->isExternallyVisible() && var->hasLinkage() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009348 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9349 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00009350 // Find a previous declaration that's not a definition.
9351 VarDecl *prev = var->getPreviousDecl();
9352 while (prev && prev->isThisDeclarationADefinition())
9353 prev = prev->getPreviousDecl();
9354
9355 if (!prev)
9356 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9357 }
9358
Reid Kleckner92fc0172014-04-30 17:10:18 +00009359 if (var->getTLSKind() == VarDecl::TLS_Static) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00009360 const Expr *Culprit;
Reid Kleckner92fc0172014-04-30 17:10:18 +00009361 if (var->getType().isDestructedType()) {
9362 // GNU C++98 edits for __thread, [basic.start.term]p3:
9363 // The type of an object with thread storage duration shall not
9364 // have a non-trivial destructor.
9365 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9366 if (getLangOpts().CPlusPlus11)
9367 Diag(var->getLocation(), diag::note_use_thread_local);
9368 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9369 !var->getInit()->isConstantInitializer(
Abramo Bagnara847c6602014-05-22 19:20:46 +00009370 Context, var->getType()->isReferenceType(), &Culprit)) {
Reid Kleckner92fc0172014-04-30 17:10:18 +00009371 // GNU C++98 edits for __thread, [basic.start.init]p4:
9372 // An object of thread storage duration shall not require dynamic
9373 // initialization.
9374 // FIXME: Need strict checking here.
Abramo Bagnara847c6602014-05-22 19:20:46 +00009375 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9376 << Culprit->getSourceRange();
Reid Kleckner92fc0172014-04-30 17:10:18 +00009377 if (getLangOpts().CPlusPlus11)
9378 Diag(var->getLocation(), diag::note_use_thread_local);
9379 }
9380
Richard Smith6ea1a4d2013-04-14 20:11:31 +00009381 }
9382
Warren Huntc3b18962014-04-08 22:30:47 +00009383 if (var->isThisDeclarationADefinition() &&
9384 ActiveTemplateInstantiations.empty()) {
9385 PragmaStack<StringLiteral *> *Stack = nullptr;
9386 int SectionFlags = PSF_Implicit | PSF_Read;
9387 if (var->getType().isConstQualified())
9388 Stack = &ConstSegStack;
9389 else if (!var->getInit()) {
9390 Stack = &BSSSegStack;
9391 SectionFlags |= PSF_Write;
9392 } else {
9393 Stack = &DataSegStack;
9394 SectionFlags |= PSF_Write;
9395 }
9396 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9397 var->addAttr(
9398 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9399 Stack->CurrentValue->getString(),
9400 Stack->CurrentPragmaLocation));
9401 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9402 if (UnifySection(SA->getName(), SectionFlags, var))
9403 var->dropAttr<SectionAttr>();
Reid Kleckner1a711b12014-07-22 00:53:05 +00009404
9405 // Apply the init_seg attribute if this has an initializer. If the
9406 // initializer turns out to not be dynamic, we'll end up ignoring this
9407 // attribute.
9408 if (CurInitSeg && var->getInit())
9409 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9410 CurInitSegLoc));
Warren Huntc3b18962014-04-08 22:30:47 +00009411 }
9412
John McCall8b7fd8f12011-01-19 11:48:09 +00009413 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009414 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00009415
Richard Smithde63d362012-11-09 23:03:14 +00009416 QualType type = var->getType();
9417 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00009418
9419 // __block variables might require us to capture a copy-initializer.
9420 if (var->hasAttr<BlocksAttr>()) {
9421 // It's currently invalid to ever have a __block variable with an
9422 // array type; should we diagnose that here?
9423
9424 // Regardless, we don't want to ignore array nesting when
9425 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00009426 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00009427 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00009428 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00009429 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00009430 ExprResult result
9431 = PerformMoveOrCopyInitialization(
9432 InitializedEntity::InitializeBlock(poi, type, false),
9433 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00009434 if (!result.isInvalid()) {
9435 result = MaybeCreateExprWithCleanups(result);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009436 Expr *init = result.getAs<Expr>();
John McCall8b7fd8f12011-01-19 11:48:09 +00009437 Context.setBlockVarCopyInits(var, init);
9438 }
9439 }
9440 }
9441
Richard Smitheda3c842011-11-07 22:16:17 +00009442 Expr *Init = var->getInit();
9443 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00009444 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00009445
Richard Smithbf830092012-10-29 18:26:47 +00009446 if (!var->getDeclContext()->isDependentContext() &&
9447 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009448 if (IsGlobal && !var->isConstexpr() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009449 !getDiagnostics().isIgnored(diag::warn_global_constructor,
9450 var->getLocation())) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00009451 // Warn about globals which don't have a constant initializer. Don't
9452 // warn about globals with a non-trivial destructor because we already
9453 // warned about them.
9454 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9455 if (!(RD && !RD->hasTrivialDestructor()) &&
9456 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9457 Diag(var->getLocation(), diag::warn_global_constructor)
9458 << Init->getSourceRange();
9459 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00009460
Richard Smithd0b4dd62011-12-19 06:19:21 +00009461 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009462 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00009463 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9464 SourceLocation DiagLoc = var->getLocation();
9465 // If the note doesn't add any useful information other than a source
9466 // location, fold it into the primary diagnostic.
9467 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9468 diag::note_invalid_subexpr_in_const_expr) {
9469 DiagLoc = Notes[0].first;
9470 Notes.clear();
9471 }
9472 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9473 << var << Init->getSourceRange();
9474 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9475 Diag(Notes[I].first, Notes[I].second);
9476 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00009477 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009478 // Check whether the initializer of a const variable of integral or
9479 // enumeration type is an ICE now, since we can't tell whether it was
9480 // initialized by a constant expression if we check later.
9481 var->checkInitIsICE();
9482 }
Richard Smitheda3c842011-11-07 22:16:17 +00009483 }
John McCall8b7fd8f12011-01-19 11:48:09 +00009484
9485 // Require the destructor.
9486 if (const RecordType *recordType = baseType->getAs<RecordType>())
9487 FinalizeVarWithDestructor(var, recordType);
9488}
9489
Richard Smithb2bc2e62011-02-21 20:05:19 +00009490/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9491/// any semantic actions necessary after any initializer has been attached.
9492void
9493Sema::FinalizeDeclaration(Decl *ThisDecl) {
9494 // Note that we are no longer parsing the initializer for this declaration.
9495 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009496
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009497 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00009498 if (!VD)
9499 return;
9500
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00009501 checkAttributesAfterMerging(*this, *VD);
9502
Hans Wennborgef2272c2014-06-18 15:55:13 +00009503 // Static locals inherit dll attributes from their function.
9504 if (VD->isStaticLocal()) {
9505 if (FunctionDecl *FD =
Richard Trieuf98341e2014-08-22 01:16:44 +00009506 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
Hans Wennborgef2272c2014-06-18 15:55:13 +00009507 if (Attr *A = getDLLAttr(FD)) {
9508 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9509 NewAttr->setInherited(true);
9510 VD->addAttr(NewAttr);
9511 }
9512 }
9513 }
9514
Nico Rieck078d2f82014-05-29 16:50:20 +00009515 // Imported static data members cannot be defined out-of-line.
9516 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) {
9517 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9518 VD->isThisDeclarationADefinition()) {
Hans Wennborge9af3162014-06-04 00:18:41 +00009519 // We allow definitions of dllimport class template static data members
9520 // with a warning.
Hans Wennborgcd959222014-06-09 18:30:28 +00009521 CXXRecordDecl *Context =
9522 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
Hans Wennborge9af3162014-06-04 00:18:41 +00009523 bool IsClassTemplateMember =
Hans Wennborgcd959222014-06-09 18:30:28 +00009524 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9525 Context->getDescribedClassTemplate();
Hans Wennborge9af3162014-06-04 00:18:41 +00009526
Nico Rieck078d2f82014-05-29 16:50:20 +00009527 Diag(VD->getLocation(),
Hans Wennborge9af3162014-06-04 00:18:41 +00009528 IsClassTemplateMember
9529 ? diag::warn_attribute_dllimport_static_field_definition
9530 : diag::err_attribute_dllimport_static_field_definition);
Nico Rieck078d2f82014-05-29 16:50:20 +00009531 Diag(IA->getLocation(), diag::note_attribute);
Hans Wennborge9af3162014-06-04 00:18:41 +00009532 if (!IsClassTemplateMember)
9533 VD->setInvalidDecl();
Nico Rieck078d2f82014-05-29 16:50:20 +00009534 }
9535 }
9536
Rafael Espindola87198cd2013-08-16 23:18:50 +00009537 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9538 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00009539 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00009540 VD->dropAttr<UsedAttr>();
9541 }
9542 }
9543
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009544 if (!VD->isInvalidDecl() &&
9545 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9546 if (const VarDecl *Def = VD->getDefinition()) {
9547 if (Def->hasAttr<AliasAttr>()) {
9548 Diag(VD->getLocation(), diag::err_tentative_after_alias)
9549 << VD->getDeclName();
9550 Diag(Def->getLocation(), diag::note_previous_definition);
9551 VD->setInvalidDecl();
9552 }
9553 }
9554 }
9555
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009556 const DeclContext *DC = VD->getDeclContext();
9557 // If there's a #pragma GCC visibility in scope, and this isn't a class
9558 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00009559 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009560 AddPushedVisibilityAttribute(VD);
9561
Richard Smithc3926172014-04-02 18:28:36 +00009562 // FIXME: Warn on unused templates.
Richard Smith6c6ef822014-04-25 19:21:40 +00009563 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9564 !isa<VarTemplatePartialSpecializationDecl>(VD))
Rafael Espindolad2ecc132013-01-03 04:29:20 +00009565 MarkUnusedFileScopedDecl(VD);
9566
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009567 // Now we have parsed the initializer and can update the table of magic
9568 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00009569 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9570 !VD->getType()->isIntegralOrEnumerationType())
9571 return;
9572
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00009573 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00009574 const Expr *MagicValueExpr = VD->getInit();
9575 if (!MagicValueExpr) {
9576 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009577 }
Rafael Espindola60470f12013-01-03 04:05:19 +00009578 llvm::APSInt MagicValueInt;
9579 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9580 Diag(I->getRange().getBegin(),
9581 diag::err_type_tag_for_datatype_not_ice)
9582 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9583 continue;
9584 }
9585 if (MagicValueInt.getActiveBits() > 64) {
9586 Diag(I->getRange().getBegin(),
9587 diag::err_type_tag_for_datatype_too_large)
9588 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9589 continue;
9590 }
9591 uint64_t MagicValue = MagicValueInt.getZExtValue();
9592 RegisterTypeTagForDatatype(I->getArgumentKind(),
9593 MagicValue,
9594 I->getMatchingCType(),
9595 I->getLayoutCompatible(),
9596 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009597 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00009598}
9599
Rafael Espindolaab417692013-07-09 12:05:01 +00009600Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9601 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009602 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009603
9604 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00009605 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009606
Craig Topperc3ec1492014-05-26 06:22:03 +00009607 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
Rafael Espindolaab417692013-07-09 12:05:01 +00009608 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00009609 if (Decl *D = Group[i]) {
9610 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9611 if (!FirstDeclaratorInGroup)
9612 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00009613 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00009614 }
Richard Smith2abf6762011-02-23 00:37:57 +00009615
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009616 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009617 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00009618 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00009619 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9620 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9621 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009622 }
David Blaikie095deba2012-11-14 01:52:05 +00009623
Rafael Espindolaab417692013-07-09 12:05:01 +00009624 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009625}
9626
9627/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9628/// group, performing any necessary semantic checking.
9629Sema::DeclGroupPtrTy
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00009630Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009631 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009632 // C++0x [dcl.spec.auto]p7:
9633 // If the type deduced for the template parameter U is not the same in each
9634 // deduction, the program is ill-formed.
9635 // FIXME: When initializer-list support is added, a distinction is needed
9636 // between the deduced type U and the deduced type which 'auto' stands for.
9637 // auto a = 0, b = { 1, 2, 3 };
9638 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009639 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009640 QualType Deduced;
9641 CanQualType DeducedCanon;
Craig Topperc3ec1492014-05-26 06:22:03 +00009642 VarDecl *DeducedDecl = nullptr;
Rafael Espindolaab417692013-07-09 12:05:01 +00009643 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009644 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9645 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009646 // Don't reissue diagnostics when instantiating a template.
9647 if (AT && D->isInvalidDecl())
9648 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009649 QualType U = AT ? AT->getDeducedType() : QualType();
9650 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009651 CanQualType UCanon = Context.getCanonicalType(U);
9652 if (Deduced.isNull()) {
9653 Deduced = U;
9654 DeducedCanon = UCanon;
9655 DeducedDecl = D;
9656 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009657 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9658 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009659 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009660 << Deduced << DeducedDecl->getDeclName()
9661 << U << D->getDeclName()
9662 << DeducedDecl->getInit()->getSourceRange()
9663 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009664 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009665 break;
9666 }
9667 }
9668 }
9669 }
9670 }
9671
Rafael Espindolaab417692013-07-09 12:05:01 +00009672 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009673
Rafael Espindolaab417692013-07-09 12:05:01 +00009674 return DeclGroupPtrTy::make(
9675 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009676}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009677
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009678void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009679 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009680}
9681
Rafael Espindolaab417692013-07-09 12:05:01 +00009682void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009683 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009684 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009685 return;
9686
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009687 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009688 return;
9689
Rafael Espindolaab417692013-07-09 12:05:01 +00009690 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009691 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009692 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009693 // additional declaration references:
9694 // 'typedef struct S {} S;'
9695 // 'typedef struct S *S;'
9696 // 'struct S *pS;'
9697 // FinalizeDeclaratorGroup adds these as separate declarations.
9698 Decl *MaybeTagDecl = Group[0];
9699 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009700 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009701 }
9702 }
9703
9704 // See if there are any new comments that are not attached to a decl.
9705 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9706 if (!Comments.empty() &&
9707 !Comments.back()->isAttached()) {
9708 // There is at least one comment that not attached to a decl.
9709 // Maybe it should be attached to one of these decls?
9710 //
9711 // Note that this way we pick up not only comments that precede the
9712 // declaration, but also comments that *follow* the declaration -- thanks to
9713 // the lookahead in the lexer: we've consumed the semicolon and looked
9714 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009715 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009716 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009717 }
9718}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009719
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009720/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9721/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009722Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009723 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009724
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009725 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009726
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009727 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009728 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009729 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009730 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009731 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009732 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9733 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009734 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009735 Diag(DS.getStorageClassSpecLoc(),
9736 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009737 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009738 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009739
Richard Smithb4a9e862013-04-12 22:46:28 +00009740 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9741 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9742 << DeclSpec::getSpecifierName(TSCS);
9743 if (DS.isConstexprSpecified())
9744 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009745 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009746
Richard Smithb4a9e862013-04-12 22:46:28 +00009747 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009748
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009749 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009750 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009751
David Blaikiebbafb8a2012-03-11 07:00:24 +00009752 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009753 // Check that there are no default arguments inside the type of this
9754 // parameter.
9755 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009756
9757 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9758 if (D.getCXXScopeSpec().isSet()) {
9759 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9760 << D.getCXXScopeSpec().getRange();
9761 D.getCXXScopeSpec().clear();
9762 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009763 }
9764
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009765 // Ensure we have a valid name
Craig Topperc3ec1492014-05-26 06:22:03 +00009766 IdentifierInfo *II = nullptr;
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009767 if (D.hasName()) {
9768 II = D.getIdentifier();
9769 if (!II) {
9770 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009771 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009772 D.setInvalidType(true);
9773 }
9774 }
9775
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009776 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009777 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009778 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9779 ForRedeclaration);
9780 LookupName(R, S);
9781 if (R.isSingleResult()) {
9782 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009783 if (PrevDecl->isTemplateParameter()) {
9784 // Maybe we will complain about the shadowed template parameter.
9785 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9786 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00009787 PrevDecl = nullptr;
John McCall48871652010-08-21 09:40:31 +00009788 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009789 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009790 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009791
Chris Lattnerd9773512009-01-21 02:38:50 +00009792 // Recover by removing the name
Craig Topperc3ec1492014-05-26 06:22:03 +00009793 II = nullptr;
9794 D.SetIdentifier(nullptr, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009795 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009796 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009797 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009798 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009799
John McCallf7b2fb52010-01-22 00:28:27 +00009800 // Temporarily put parameter variables in the translation unit, not
9801 // the enclosing context. This prevents them from accidentally
9802 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009803 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009804 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009805 D.getIdentifierLoc(), II,
9806 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009807 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009808
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009809 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009810 New->setInvalidDecl();
9811
9812 assert(S->isFunctionPrototypeScope());
9813 assert(S->getFunctionPrototypeDepth() >= 1);
9814 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9815 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009816
Douglas Gregor91f84212008-12-11 16:49:14 +00009817 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009818 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009819 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009820 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009821
Douglas Gregor758a8692009-06-17 21:51:59 +00009822 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009823
Douglas Gregor41866812011-09-12 18:37:38 +00009824 if (D.getDeclSpec().isModulePrivateSpecified())
9825 Diag(New->getLocation(), diag::err_module_private_local)
9826 << 1 << New->getDeclName()
9827 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9828 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9829
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009830 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009831 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9832 }
John McCall48871652010-08-21 09:40:31 +00009833 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009834}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009835
John McCalla3ccba02010-06-04 11:21:44 +00009836/// \brief Synthesizes a variable for a parameter arising from a
9837/// typedef.
9838ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9839 SourceLocation Loc,
9840 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009841 /* FIXME: setting StartLoc == Loc.
9842 Would it be worth to modify callers so as to provide proper source
9843 location for the unnamed parameters, embedding the parameter's type? */
Craig Topperc3ec1492014-05-26 06:22:03 +00009844 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
John McCalla3ccba02010-06-04 11:21:44 +00009845 T, Context.getTrivialTypeSourceInfo(T, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +00009846 SC_None, nullptr);
John McCalla3ccba02010-06-04 11:21:44 +00009847 Param->setImplicit();
9848 return Param;
9849}
9850
John McCallc5990642010-08-24 09:05:15 +00009851void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9852 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009853 // Don't diagnose unused-parameter errors in template instantiations; we
9854 // will already have done so in the template itself.
9855 if (!ActiveTemplateInstantiations.empty())
9856 return;
9857
9858 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009859 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009860 !(*Param)->hasAttr<UnusedAttr>()) {
9861 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9862 << (*Param)->getDeclName();
9863 }
9864 }
9865}
9866
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009867void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9868 ParmVarDecl * const *ParamEnd,
9869 QualType ReturnTy,
9870 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009871 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009872 return;
9873
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009874 // Warn if the return value is pass-by-value and larger than the specified
9875 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009876 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009877 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009878 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009879 Diag(D->getLocation(), diag::warn_return_value_size)
9880 << D->getDeclName() << Size;
9881 }
9882
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009883 // Warn if any parameter is pass-by-value and larger than the specified
9884 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009885 for (; Param != ParamEnd; ++Param) {
9886 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009887 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009888 continue;
9889 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009890 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009891 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9892 << (*Param)->getDeclName() << Size;
9893 }
9894}
9895
Abramo Bagnaradff19302011-03-08 08:55:46 +00009896ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9897 SourceLocation NameLoc, IdentifierInfo *Name,
9898 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009899 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009900 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009901 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009902 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009903 T->isObjCLifetimeType()) {
9904
9905 Qualifiers::ObjCLifetime lifetime;
9906
9907 // Special cases for arrays:
9908 // - if it's const, use __unsafe_unretained
9909 // - otherwise, it's an error
9910 if (T->isArrayType()) {
9911 if (!T.isConstQualified()) {
9912 DelayedDiagnostics.add(
9913 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009914 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009915 }
9916 lifetime = Qualifiers::OCL_ExplicitNone;
9917 } else {
9918 lifetime = T->getObjCARCImplicitLifetime();
9919 }
9920 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009921 }
9922
Abramo Bagnaradff19302011-03-08 08:55:46 +00009923 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009924 Context.getAdjustedParameterType(T),
9925 TSInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009926 StorageClass, nullptr);
Douglas Gregor940bca72010-04-12 07:48:19 +00009927
9928 // Parameters can not be abstract class types.
9929 // For record types, this is done by the AbstractClassUsageDiagnoser once
9930 // the class has been completely parsed.
9931 if (!CurContext->isRecord() &&
9932 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9933 AbstractParamType))
9934 New->setInvalidDecl();
9935
9936 // Parameter declarators cannot be interface types. All ObjC objects are
9937 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009938 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009939 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009940 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009941 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009942 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009943 T = Context.getObjCObjectPointerType(T);
9944 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009945 }
9946
9947 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9948 // duration shall not be qualified by an address-space qualifier."
9949 // Since all parameters have automatic store duration, they can not have
9950 // an address space.
9951 if (T.getAddressSpace() != 0) {
Fraser Cormack01648e02014-04-15 11:38:29 +00009952 // OpenCL allows function arguments declared to be an array of a type
9953 // to be qualified with an address space.
9954 if (!(getLangOpts().OpenCL && T->isArrayType())) {
9955 Diag(NameLoc, diag::err_arg_with_address_space);
9956 New->setInvalidDecl();
9957 }
Douglas Gregor940bca72010-04-12 07:48:19 +00009958 }
9959
9960 return New;
9961}
9962
Douglas Gregor170512f2009-04-01 23:51:29 +00009963void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9964 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009965 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009966
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009967 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9968 // for a K&R function.
9969 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009970 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009971 --i;
Craig Topperc3ec1492014-05-26 06:22:03 +00009972 if (FTI.Params[i].Param == nullptr) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009973 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009974 llvm::raw_svector_ostream(Code)
9975 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9976 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9977 << FTI.Params[i].Ident
9978 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009979
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009980 // Implicitly declare the argument as type 'int' for lack of a better
9981 // type.
John McCall084e83d2011-03-24 11:26:52 +00009982 AttributeFactory attrs;
9983 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009984 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009985 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009986 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9987 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009988 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009989 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9990 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009991 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009992 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9993 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009994 }
9995 }
Mike Stump11289f42009-09-09 15:08:12 +00009996 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009997}
9998
Richard Smith79a52e52012-04-17 22:30:01 +00009999Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010000 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +000010001 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +000010002 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +000010003
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000010004 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010005 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +000010006 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000010007}
10008
Hans Wennborga926d842014-05-23 20:37:38 +000010009void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10010 Consumer.HandleInlineMethodDefinition(D);
10011}
10012
Anders Carlsson2a45e402012-12-18 01:29:20 +000010013static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10014 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +000010015 // Don't warn about invalid declarations.
10016 if (FD->isInvalidDecl())
10017 return false;
Anders Carlssona0388252009-12-09 03:44:46 +000010018
Anders Carlsson31c7e882009-12-09 03:30:09 +000010019 // Or declarations that aren't global.
10020 if (!FD->isGlobal())
10021 return false;
Anders Carlssona0388252009-12-09 03:44:46 +000010022
Anders Carlsson31c7e882009-12-09 03:30:09 +000010023 // Don't warn about C++ member functions.
10024 if (isa<CXXMethodDecl>(FD))
10025 return false;
Anders Carlssona0388252009-12-09 03:44:46 +000010026
Anders Carlsson31c7e882009-12-09 03:30:09 +000010027 // Don't warn about 'main'.
10028 if (FD->isMain())
10029 return false;
Anders Carlssona0388252009-12-09 03:44:46 +000010030
Anders Carlsson31c7e882009-12-09 03:30:09 +000010031 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +000010032 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +000010033 return false;
Anders Carlssona0388252009-12-09 03:44:46 +000010034
10035 // Don't warn about function templates.
10036 if (FD->getDescribedFunctionTemplate())
10037 return false;
10038
10039 // Don't warn about function template specializations.
10040 if (FD->isFunctionTemplateSpecialization())
10041 return false;
10042
Tanya Lattner4bfc3552012-07-26 00:08:28 +000010043 // Don't warn for OpenCL kernels.
10044 if (FD->hasAttr<OpenCLKernelAttr>())
10045 return false;
Richard Smith541b38b2013-09-20 01:15:31 +000010046
Anders Carlsson31c7e882009-12-09 03:30:09 +000010047 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +000010048 for (const FunctionDecl *Prev = FD->getPreviousDecl();
10049 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +000010050 // Ignore any declarations that occur in function or method
10051 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +000010052 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +000010053 continue;
Richard Smith541b38b2013-09-20 01:15:31 +000010054
Anders Carlsson31c7e882009-12-09 03:30:09 +000010055 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +000010056 if (FD->getNumParams() == 0)
10057 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +000010058 break;
10059 }
Richard Smith541b38b2013-09-20 01:15:31 +000010060
Anders Carlsson31c7e882009-12-09 03:30:09 +000010061 return MissingPrototype;
10062}
10063
Rafael Espindolad53ffa02013-10-22 21:39:03 +000010064void
10065Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10066 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +000010067 // Don't complain if we're in GNU89 mode and the previous definition
10068 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +000010069 const FunctionDecl *Definition = EffectiveDefinition;
10070 if (!Definition)
10071 if (!FD->isDefined(Definition))
10072 return;
10073
10074 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +000010075 return;
10076
10077 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10078 Definition->getStorageClass() == SC_Extern)
10079 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +000010080 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +000010081 else
10082 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10083
10084 Diag(Definition->getLocation(), diag::note_previous_definition);
10085 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +000010086}
Faisal Valia17d19f2013-11-07 05:17:06 +000010087
10088
Faisal Valic1a6dc42013-10-23 16:10:50 +000010089static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10090 Sema &S) {
10091 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +000010092
10093 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +000010094 LSI->CallOperator = CallOperator;
10095 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +000010096 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +000010097 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10098
10099 if (LCD == LCD_None)
10100 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10101 else if (LCD == LCD_ByCopy)
10102 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10103 else if (LCD == LCD_ByRef)
10104 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10105 DeclarationNameInfo DNI = CallOperator->getNameInfo();
10106
10107 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10108 LSI->Mutable = !CallOperator->isConst();
10109
Faisal Valia17d19f2013-11-07 05:17:06 +000010110 // Add the captures to the LSI so they can be noted as already
10111 // captured within tryCaptureVar.
Alexey Bataev39c81e22014-08-28 04:28:19 +000010112 auto I = LambdaClass->field_begin();
Aaron Ballman6def98a2014-03-13 17:08:33 +000010113 for (const auto &C : LambdaClass->captures()) {
10114 if (C.capturesVariable()) {
10115 VarDecl *VD = C.getCapturedVar();
Faisal Valia17d19f2013-11-07 05:17:06 +000010116 if (VD->isInitCapture())
10117 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10118 QualType CaptureType = VD->getType();
Aaron Ballman6def98a2014-03-13 17:08:33 +000010119 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
Faisal Valia17d19f2013-11-07 05:17:06 +000010120 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
Aaron Ballman6def98a2014-03-13 17:08:33 +000010121 /*RefersToEnclosingLocal*/true, C.getLocation(),
10122 /*EllipsisLoc*/C.isPackExpansion()
10123 ? C.getEllipsisLoc() : SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010124 CaptureType, /*Expr*/ nullptr);
10125
Aaron Ballman6def98a2014-03-13 17:08:33 +000010126 } else if (C.capturesThis()) {
10127 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010128 S.getCurrentThisType(), /*Expr*/ nullptr);
Alexey Bataev39c81e22014-08-28 04:28:19 +000010129 } else {
10130 LSI->addVLATypeCapture(C.getLocation(), I->getType());
Faisal Valia17d19f2013-11-07 05:17:06 +000010131 }
Alexey Bataev39c81e22014-08-28 04:28:19 +000010132 ++I;
Faisal Valia17d19f2013-11-07 05:17:06 +000010133 }
Faisal Valic1a6dc42013-10-23 16:10:50 +000010134}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +000010135
John McCall48871652010-08-21 09:40:31 +000010136Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +000010137 // Clear the last template instantiation error context.
10138 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10139
Douglas Gregor17a7c122009-06-24 00:54:41 +000010140 if (!D)
10141 return D;
Craig Topperc3ec1492014-05-26 06:22:03 +000010142 FunctionDecl *FD = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +000010143
John McCall48871652010-08-21 09:40:31 +000010144 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +000010145 FD = FunTmpl->getTemplatedDecl();
10146 else
John McCall48871652010-08-21 09:40:31 +000010147 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +000010148 // If we are instantiating a generic lambda call operator, push
10149 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +000010150 // that's already been calculated (ActOnLambdaExpr) to prime the current
10151 // LambdaScopeInfo.
10152 // When the template operator is being specialized, the LambdaScopeInfo,
10153 // has to be properly restored so that tryCaptureVariable doesn't try
10154 // and capture any new variables. In addition when calculating potential
10155 // captures during transformation of nested lambdas, it is necessary to
10156 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +000010157 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +000010158 assert(ActiveTemplateInstantiations.size() &&
10159 "There should be an active template instantiation on the stack "
10160 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +000010161 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +000010162 }
10163 else
10164 // Enter a new function scope
10165 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +000010166
Douglas Gregorcad304ba2008-10-29 15:10:40 +000010167 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +000010168 if (!FD->isLateTemplateParsed())
10169 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +000010170
Douglas Gregor75a45ba2009-02-16 17:45:42 +000010171 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010172 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +000010173 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10174 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +000010175 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +000010176 FD->setInvalidDecl();
10177 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +000010178 }
10179
Eli Friedman9ad72442009-03-04 07:30:59 +000010180 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +000010181 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +000010182 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +000010183 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +000010184 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +000010185 RequireCompleteType(FD->getLocation(), ResultType,
10186 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +000010187 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +000010188
Douglas Gregorf1b876d2009-03-31 16:35:03 +000010189 // GNU warning -Wmissing-prototypes:
10190 // Warn if a global function is defined without a previous
10191 // prototype declaration. This warning is issued even if the
10192 // definition itself provides a prototype. The aim is to detect
10193 // global functions that fail to be declared in header files.
Craig Topperc3ec1492014-05-26 06:22:03 +000010194 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
Anders Carlsson2a45e402012-12-18 01:29:20 +000010195 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +000010196 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +000010197
Anders Carlsson2a45e402012-12-18 01:29:20 +000010198 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +000010199 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +000010200 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +000010201 if (TypeSourceInfo *TI =
10202 PossibleZeroParamPrototype->getTypeSourceInfo()) {
10203 TypeLoc TL = TI->getTypeLoc();
10204 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10205 Diag(PossibleZeroParamPrototype->getLocation(),
10206 diag::note_declaration_not_a_prototype)
10207 << PossibleZeroParamPrototype
10208 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10209 }
Anders Carlsson2a45e402012-12-18 01:29:20 +000010210 }
10211 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +000010212
Douglas Gregor67da0d92009-05-15 17:59:04 +000010213 if (FnBodyScope)
10214 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +000010215
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000010216 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +000010217 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10218 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000010219
10220 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010221 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +000010222 Param->setOwningFunction(FD);
10223
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000010224 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +000010225 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000010226 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +000010227
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +000010228 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +000010229 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +000010230 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000010231
James Molloy6f8780b2012-02-29 10:24:19 +000010232 // If we had any tags defined in the function prototype,
10233 // introduce them into the function scope.
10234 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +000010235 for (ArrayRef<NamedDecl *>::iterator
10236 I = FD->getDeclsInPrototypeScope().begin(),
10237 E = FD->getDeclsInPrototypeScope().end();
10238 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +000010239 NamedDecl *D = *I;
10240
10241 // Some of these decls (like enums) may have been pinned to the translation unit
10242 // for lack of a real context earlier. If so, remove from the translation unit
10243 // and reattach to the current context.
10244 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10245 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +000010246 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10247 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +000010248 Context.getTranslationUnitDecl()->removeDecl(D);
10249 break;
10250 }
10251 }
10252 // Either way, reassign the lexical decl context to our FunctionDecl.
10253 D->setLexicalDeclContext(CurContext);
10254 }
10255
10256 // If the decl has a non-null name, make accessible in the current scope.
10257 if (!D->getName().empty())
10258 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10259
10260 // Similarly, dive into enums and fish their constants out, making them
10261 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +000010262 if (auto *ED = dyn_cast<EnumDecl>(D)) {
10263 for (auto *EI : ED->enumerators())
10264 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +000010265 }
10266 }
10267 }
10268
Richard Smith79a52e52012-04-17 22:30:01 +000010269 // Ensure that the function's exception specification is instantiated.
10270 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10271 ResolveExceptionSpec(D->getLocation(), FPT);
10272
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010273 // dllimport cannot be applied to non-inline function definitions.
Hans Wennborg7f26fa62014-05-19 20:14:13 +000010274 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10275 !FD->isTemplateInstantiation()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010276 assert(!FD->hasAttr<DLLExportAttr>());
10277 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10278 FD->setInvalidDecl();
10279 return D;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +000010280 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +000010281 // We want to attach documentation to original Decl (which might be
10282 // a function template).
10283 ActOnDocumentableDecl(D);
Fariborz Jahanian3451df82014-05-28 17:02:35 +000010284 if (getCurLexicalContext()->isObjCContainer() &&
10285 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10286 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10287 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10288
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +000010289 return D;
Chris Lattnere168f762006-11-10 05:29:30 +000010290}
10291
Douglas Gregor6fd1b182010-05-15 06:01:05 +000010292/// \brief Given the set of return statements within a function body,
10293/// compute the variables that are subject to the named return value
10294/// optimization.
10295///
10296/// Each of the variables that is subject to the named return value
10297/// optimization will be marked as NRVO variables in the AST, and any
10298/// return statement that has a marked NRVO variable as its NRVO candidate can
10299/// use the named return value optimization.
10300///
10301/// This function applies a very simplistic algorithm for NRVO: if every return
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010302/// statement in the scope of a variable has the same NRVO candidate, that
10303/// candidate is an NRVO variable.
Douglas Gregor49695f02011-09-06 20:46:03 +000010304void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +000010305 ReturnStmt **Returns = Scope->Returns.data();
10306
John McCallaab3e412010-08-25 08:40:02 +000010307 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010308 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10309 if (!NRVOCandidate->isNRVOVariable())
10310 Returns[I]->setNRVOCandidate(nullptr);
10311 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +000010312 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +000010313}
10314
Richard Smith8e6002f2014-03-12 23:14:33 +000010315bool Sema::canDelayFunctionBody(const Declarator &D) {
10316 // We can't delay parsing the body of a constexpr function template (yet).
10317 if (D.getDeclSpec().isConstexprSpecified())
10318 return false;
10319
10320 // We can't delay parsing the body of a function template with a deduced
10321 // return type (yet).
10322 if (D.getDeclSpec().containsPlaceholderType()) {
10323 // If the placeholder introduces a non-deduced trailing return type,
10324 // we can still delay parsing it.
10325 if (D.getNumTypeObjects()) {
10326 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10327 if (Outer.Kind == DeclaratorChunk::Function &&
10328 Outer.Fun.hasTrailingReturnType()) {
10329 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10330 return Ty.isNull() || !Ty->isUndeducedType();
10331 }
10332 }
10333 return false;
10334 }
10335
10336 return true;
10337}
10338
Richard Smith1ab34b32012-11-19 21:13:18 +000010339bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +000010340 // We cannot skip the body of a function (or function template) which is
10341 // constexpr, since we may need to evaluate its body in order to parse the
10342 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +000010343 // We cannot skip the body of a function with an undeduced return type,
10344 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +000010345 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +000010346 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +000010347 return false;
10348 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +000010349}
10350
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +000010351Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +000010352 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +000010353 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +000010354 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +000010355 MD->setHasSkippedBody();
Craig Topperc3ec1492014-05-26 06:22:03 +000010356 return ActOnFinishFunctionBody(Decl, nullptr);
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +000010357}
10358
John McCallfaf5fb42010-08-26 23:41:50 +000010359Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010360 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +000010361}
10362
John McCallb268a282010-08-23 23:25:46 +000010363Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10364 bool IsInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010365 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
Douglas Gregorc45a40a2009-08-22 00:34:47 +000010366
Ted Kremenek0b405322010-03-23 00:13:23 +000010367 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Craig Topperc3ec1492014-05-26 06:22:03 +000010368 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
Ted Kremenek918fe842010-03-20 21:06:02 +000010369
Douglas Gregorc45a40a2009-08-22 00:34:47 +000010370 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +000010371 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +000010372
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010373 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +000010374 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +000010375 // If the function has a deduced result type but contains no 'return'
10376 // statements, the result type as written must be exactly 'auto', and
10377 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +000010378 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +000010379 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +000010380 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +000010381 FD->setInvalidDecl();
10382 } else {
10383 // Substitute 'void' for the 'auto' in the type.
10384 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +000010385 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +000010386 Context.adjustDeducedFunctionResultType(
10387 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +000010388 }
10389 }
10390
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000010391 // The only way to be included in UndefinedButUsed is if there is an
10392 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +000010393 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +000010394 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +000010395 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000010396 UndefinedButUsed.erase(FD);
10397 else if (FD->isInlined() &&
10398 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10399 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10400 UndefinedButUsed.erase(FD);
10401 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +000010402
John McCall5ed3caf2012-02-14 19:50:52 +000010403 // If the function implicitly returns zero (like 'main') or is naked,
10404 // don't complain about missing return statements.
10405 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +000010406 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +000010407
Francois Pichet3abc9b82011-05-11 02:14:46 +000010408 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +000010409 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +000010410 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Richard Smith1b98ccc2014-07-19 01:39:17 +000010411 Diag(FD->getLocation(), diag::ext_pure_function_definition);
Francois Pichet3abc9b82011-05-11 02:14:46 +000010412
Douglas Gregor88d292c2010-05-13 16:44:06 +000010413 if (!FD->isInvalidDecl()) {
Reid Kleckner121b1a12014-04-30 16:31:28 +000010414 // Don't diagnose unused parameters of defaulted or deleted functions.
10415 if (Body)
10416 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010417 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +000010418 FD->getReturnType(), FD);
10419
Douglas Gregor88d292c2010-05-13 16:44:06 +000010420 // If this is a constructor, we need a vtable.
10421 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10422 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +000010423
Jordan Rosed39e5f12012-07-02 21:19:23 +000010424 // Try to apply the named return value optimization. We have to check
10425 // if we can do this here because lambdas keep return statements around
10426 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +000010427 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +000010428 !FD->isDependentContext())
10429 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +000010430 }
10431
Douglas Gregor21f46922012-02-08 20:17:14 +000010432 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10433 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +000010434 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +000010435 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +000010436 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010437 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010438 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010439 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +000010440 MD->getReturnType(), MD);
10441
Douglas Gregore3f3ea02011-09-06 20:33:37 +000010442 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +000010443 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010444 }
Jordan Rose2afd6612012-10-19 16:05:26 +000010445 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +000010446 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10447 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +000010448 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +000010449 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010450 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010451 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +000010452 bool isDesignated =
10453 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010454 assert(isDesignated && InitMethod);
10455 (void)isDesignated;
Argyrios Kyrtzidisde103662014-04-16 18:32:51 +000010456
10457 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10458 auto IFace = MD->getClassInterface();
10459 if (!IFace)
10460 return false;
10461 auto SuperD = IFace->getSuperClass();
10462 if (!SuperD)
10463 return false;
10464 return SuperD->getIdentifier() ==
10465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10466 };
10467 // Don't issue this warning for unavailable inits or direct subclasses
10468 // of NSObject.
10469 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +000010470 Diag(MD->getLocation(),
10471 diag::warn_objc_designated_init_missing_super_call);
10472 Diag(InitMethod->getLocation(),
10473 diag::note_objc_designated_init_marked_here);
10474 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010475 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10476 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +000010477 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +000010478 // Don't issue this warning for unavaialable inits.
10479 if (!MD->isUnavailable())
10480 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +000010481 getCurFunction()->ObjCWarnForNoInitDelegation = false;
10482 }
Ted Kremenek5a201952009-02-07 01:47:29 +000010483 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +000010484 return nullptr;
Ted Kremenek5a201952009-02-07 01:47:29 +000010485 }
Douglas Gregor67da0d92009-05-15 17:59:04 +000010486
Jordan Rose2afd6612012-10-19 16:05:26 +000010487 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +000010488 "This should only be set for ObjC methods, which should have been "
10489 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +000010490
Chris Lattnere2473062007-05-28 06:28:18 +000010491 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +000010492 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000010493 // C++ constructors that have function-try-blocks can't have return
10494 // statements in the handlers of that block. (C++ [except.handle]p14)
10495 // Verify this.
10496 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10497 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10498
Richard Smithdef8bdb2011-08-12 18:44:32 +000010499 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +000010500 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000010501 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +000010502 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +000010503
John McCalldeb646e2010-08-04 01:04:25 +000010504 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10505 if (!Destructor->getParent()->isDependentType())
10506 CheckDestructor(Destructor);
10507
John McCalla6309952010-03-16 21:39:52 +000010508 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10509 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +000010510 }
Douglas Gregor9a28e842010-03-01 23:15:13 +000010511
10512 // If any errors have occurred, clear out any temporaries that may have
10513 // been leftover. This ensures that these temporaries won't be picked up for
10514 // deletion in some later function.
Alp Tokerb6cc5922014-05-03 03:45:55 +000010515 if (getDiagnostics().hasErrorOccurred() ||
10516 getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +000010517 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010518 }
Alp Tokerb6cc5922014-05-03 03:45:55 +000010519 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010520 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +000010521 // Since the body is valid, issue any analysis-based warnings that are
10522 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +000010523 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +000010524 }
10525
Richard Smith3607ffe2012-02-13 03:54:03 +000010526 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10527 (!CheckConstexprFunctionDecl(FD) ||
10528 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +000010529 FD->setInvalidDecl();
10530
Hans Wennborgd62cdd2c2014-09-04 22:16:40 +000010531 if (FD && FD->hasAttr<NakedAttr>()) {
10532 for (const Stmt *S : Body->children()) {
Ehsan Akhgari5c00c312014-09-09 02:49:40 +000010533 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
Hans Wennborgd62cdd2c2014-09-04 22:16:40 +000010534 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10535 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10536 FD->setInvalidDecl();
10537 break;
10538 }
10539 }
10540 }
10541
John McCall28fc7092011-11-10 05:35:25 +000010542 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +000010543 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +000010544 assert(MaybeODRUseExprs.empty() &&
10545 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +000010546 }
10547
John McCalle99d5f32010-03-25 22:08:03 +000010548 if (!IsInstantiation)
10549 PopDeclContext();
10550
Eli Friedman71c80552012-01-05 03:35:19 +000010551 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +000010552 // If any errors have occurred, clear out any temporaries that may have
10553 // been leftover. This ensures that these temporaries won't be picked up for
10554 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +000010555 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +000010556 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +000010557 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +000010558
John McCall48871652010-08-21 09:40:31 +000010559 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +000010560}
10561
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010562
10563/// When we finish delayed parsing of an attribute, we must attach it to the
10564/// relevant Decl.
10565void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10566 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000010567 // Always attach attributes to the underlying decl.
10568 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10569 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +000010570 ProcessDeclAttributeList(S, D, Attrs.getList());
10571
10572 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10573 if (Method->isStatic())
10574 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010575}
10576
10577
Chris Lattnerac18be92006-11-20 06:49:47 +000010578/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10579/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +000010580NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +000010581 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010582 // Before we produce a declaration for an implicitly defined
10583 // function, see whether there was a locally-scoped declaration of
10584 // this name as a function or variable. If so, use that
10585 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +000010586 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10587 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10588 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10589 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010590 }
10591
Chris Lattner00e26072008-05-05 21:18:06 +000010592 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +000010593 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +000010594 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +000010595 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010596 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +000010597 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +000010598 else
Hans Wennborg70a13242011-12-08 15:56:07 +000010599 diag_id = diag::warn_implicit_function_decl;
10600 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +000010601
Hans Wennborg70a13242011-12-08 15:56:07 +000010602 // Because typo correction is expensive, only do it if the implicit
10603 // function declaration is going to be treated as an error.
10604 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10605 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000010606 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +000010607 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000010608 LookupOrdinaryName, S, nullptr, Validator,
John Thompson2255f2c2014-04-23 12:57:01 +000010609 CTK_NonError)))
Richard Smithf9b15102013-08-17 00:46:16 +000010610 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10611 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +000010612 }
10613
Chris Lattnerac18be92006-11-20 06:49:47 +000010614 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +000010615 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +000010616 AttributeFactory attrFactory;
10617 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +000010618 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +000010619 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10620 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010621 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +000010622 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010623 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +000010624 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010625 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10626 /*IsAmbiguous=*/false,
Richard Smith151b8a32014-04-07 15:16:58 +000010627 /*LParenLoc=*/NoLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010628 /*Params=*/nullptr,
Richard Smith151b8a32014-04-07 15:16:58 +000010629 /*NumParams=*/0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010630 /*EllipsisLoc=*/NoLoc,
10631 /*RParenLoc=*/NoLoc,
10632 /*TypeQuals=*/0,
10633 /*RefQualifierIsLvalueRef=*/true,
10634 /*RefQualifierLoc=*/NoLoc,
10635 /*ConstQualifierLoc=*/NoLoc,
10636 /*VolatileQualifierLoc=*/NoLoc,
10637 /*MutableLoc=*/NoLoc,
10638 EST_None,
10639 /*ESpecLoc=*/NoLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010640 /*Exceptions=*/nullptr,
10641 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010642 /*NumExceptions=*/0,
Craig Topperc3ec1492014-05-26 06:22:03 +000010643 /*NoexceptExpr=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010644 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +000010645 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010646 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010647 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010648
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010649 // Insert this function into translation-unit scope.
10650
10651 DeclContext *PrevDC = CurContext;
10652 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010653
Jordan Rosed03d99d2013-03-05 01:27:54 +000010654 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010655 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010656
10657 CurContext = PrevDC;
10658
Douglas Gregore711f702009-02-14 18:57:46 +000010659 AddKnownFunctionAttributes(FD);
10660
Steve Naroff3913ea42008-04-04 14:32:09 +000010661 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010662}
10663
Douglas Gregore711f702009-02-14 18:57:46 +000010664/// \brief Adds any function attributes that we know a priori based on
10665/// the declaration of this function.
10666///
10667/// These attributes can apply both to implicitly-declared builtins
10668/// (like __builtin___printf_chk) or to library-declared functions
10669/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010670///
10671/// We need to check for duplicate attributes both here and where user-written
10672/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010673void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10674 if (FD->isInvalidDecl())
10675 return;
10676
10677 // If this is a built-in function, map its builtin attributes to
10678 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010679 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010680 // Handle printf-formatting attributes.
10681 unsigned FormatIdx;
10682 bool HasVAListArg;
10683 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010684 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010685 const char *fmt = "printf";
10686 unsigned int NumParams = FD->getNumParams();
10687 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10688 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10689 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010690 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010691 &Context.Idents.get(fmt),
10692 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010693 HasVAListArg ? 0 : FormatIdx+2,
10694 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010695 }
Douglas Gregore711f702009-02-14 18:57:46 +000010696 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010697 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10698 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010699 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010700 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010701 &Context.Idents.get("scanf"),
10702 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010703 HasVAListArg ? 0 : FormatIdx+2,
10704 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010705 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010706
10707 // Mark const if we don't care about errno and that is the only
10708 // thing preventing the function from being const. This allows
10709 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010710 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010711 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010712 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010713 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010714 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010715
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010716 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010717 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010718 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10719 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010720 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010721 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010722 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010723 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010724 }
10725
10726 IdentifierInfo *Name = FD->getIdentifier();
10727 if (!Name)
10728 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010729 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010730 FD->getDeclContext()->isTranslationUnit()) ||
10731 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010732 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010733 LinkageSpecDecl::lang_c)) {
10734 // Okay: this could be a libc/libm/Objective-C function we know
10735 // about.
10736 } else
10737 return;
10738
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010739 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010740 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010741 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010742 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010743 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010744 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010745 Name->isStr("vasprintf") ? 0 : 3,
10746 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010747 }
Jordan Rose742c6072012-08-08 21:17:31 +000010748
10749 if (Name->isStr("__CFStringMakeConstantString")) {
10750 // We already have a __builtin___CFStringMakeConstantString,
10751 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010752 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010753 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10754 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010755 }
Douglas Gregore711f702009-02-14 18:57:46 +000010756}
Chris Lattner302b4be2006-11-19 02:31:38 +000010757
John McCall703a3f82009-10-24 08:00:42 +000010758TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010759 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010760 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010761 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010762
John McCallbcd03502009-12-07 02:54:59 +000010763 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010764 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010765 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010766 }
10767
Chris Lattner18b19622007-01-22 07:39:13 +000010768 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010769 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010770 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010771 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010772 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010773 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010774
John McCall04fcd0d2011-02-01 08:20:08 +000010775 // Bail out immediately if we have an invalid declaration.
10776 if (D.isInvalidType()) {
10777 NewTD->setInvalidDecl();
10778 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010779 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010780
Douglas Gregor41866812011-09-12 18:37:38 +000010781 if (D.getDeclSpec().isModulePrivateSpecified()) {
10782 if (CurContext->isFunctionOrMethod())
10783 Diag(NewTD->getLocation(), diag::err_module_private_local)
10784 << 2 << NewTD->getDeclName()
10785 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10786 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10787 else
10788 NewTD->setModulePrivate();
10789 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010790
John McCall04fcd0d2011-02-01 08:20:08 +000010791 // C++ [dcl.typedef]p8:
10792 // If the typedef declaration defines an unnamed class (or
10793 // enum), the first typedef-name declared by the declaration
10794 // to be that class type (or enum type) is used to denote the
10795 // class type (or enum type) for linkage purposes only.
10796 // We need to check whether the type was declared in the declaration.
10797 switch (D.getDeclSpec().getTypeSpecType()) {
10798 case TST_enum:
10799 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010800 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010801 case TST_union:
10802 case TST_class: {
10803 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10804
10805 // Do nothing if the tag is not anonymous or already has an
10806 // associated typedef (from an earlier typedef in this decl group).
10807 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010808 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010809
10810 // A well-formed anonymous tag must always be a TUK_Definition.
10811 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10812
10813 // The type must match the tag exactly; no qualifiers allowed.
10814 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10815 break;
10816
John McCall2575d882014-01-30 01:12:53 +000010817 // If we've already computed linkage for the anonymous tag, then
10818 // adding a typedef name for the anonymous decl can change that
10819 // linkage, which might be a serious problem. Diagnose this as
10820 // unsupported and ignore the typedef name. TODO: we should
10821 // pursue this as a language defect and establish a formal rule
10822 // for how to handle it.
10823 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10824 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10825
10826 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +000010827 tagLoc = getLocForEndOfToken(tagLoc);
John McCall2575d882014-01-30 01:12:53 +000010828
10829 llvm::SmallString<40> textToInsert;
10830 textToInsert += ' ';
10831 textToInsert += D.getIdentifier()->getName();
10832 Diag(tagLoc, diag::note_typedef_changes_linkage)
10833 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10834 break;
10835 }
10836
John McCall04fcd0d2011-02-01 08:20:08 +000010837 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010838 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010839 break;
10840 }
10841
10842 default:
10843 break;
10844 }
10845
Steve Narofff93b6722007-08-28 20:14:24 +000010846 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010847}
10848
Douglas Gregord9034f02009-05-14 16:41:31 +000010849
Richard Smith4b38ded2012-03-14 23:13:10 +000010850/// \brief Check that this is a valid underlying type for an enum declaration.
10851bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10852 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10853 QualType T = TI->getType();
10854
Eli Friedman52f32b92012-12-18 02:37:32 +000010855 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010856 return false;
10857
Eli Friedman52f32b92012-12-18 02:37:32 +000010858 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10859 if (BT->isInteger())
10860 return false;
10861
Richard Smith4b38ded2012-03-14 23:13:10 +000010862 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10863 return true;
10864}
10865
10866/// Check whether this is a valid redeclaration of a previous enumeration.
10867/// \return true if the redeclaration was invalid.
10868bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10869 QualType EnumUnderlyingTy,
10870 const EnumDecl *Prev) {
10871 bool IsFixed = !EnumUnderlyingTy.isNull();
10872
10873 if (IsScoped != Prev->isScoped()) {
10874 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10875 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010876 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010877 return true;
10878 }
10879
10880 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010881 if (!EnumUnderlyingTy->isDependentType() &&
10882 !Prev->getIntegerType()->isDependentType() &&
10883 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010884 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010885 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010886 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10887 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010888 Diag(Prev->getLocation(), diag::note_previous_declaration)
10889 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010890 return true;
10891 }
10892 } else if (IsFixed != Prev->isFixed()) {
10893 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10894 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010895 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010896 return true;
10897 }
10898
10899 return false;
10900}
10901
Joao Matosdc86f942012-08-31 18:45:21 +000010902/// \brief Get diagnostic %select index for tag kind for
10903/// redeclaration diagnostic message.
10904/// WARNING: Indexes apply to particular diagnostics only!
10905///
10906/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010907static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010908 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010909 case TTK_Struct: return 0;
10910 case TTK_Interface: return 1;
10911 case TTK_Class: return 2;
10912 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010913 }
Joao Matosdc86f942012-08-31 18:45:21 +000010914}
10915
10916/// \brief Determine if tag kind is a class-key compatible with
10917/// class for redeclaration (class, struct, or __interface).
10918///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010919/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010920static bool isClassCompatTagKind(TagTypeKind Tag)
10921{
10922 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10923}
10924
Douglas Gregord9034f02009-05-14 16:41:31 +000010925/// \brief Determine whether a tag with a given kind is acceptable
10926/// as a redeclaration of the given tag declaration.
10927///
10928/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010929bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010930 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010931 SourceLocation NewTagLoc,
10932 const IdentifierInfo &Name) {
10933 // C++ [dcl.type.elab]p3:
10934 // The class-key or enum keyword present in the
10935 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010936 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010937 // refers. This rule also applies to the form of
10938 // elaborated-type-specifier that declares a class-name or
10939 // friend class since it can be construed as referring to the
10940 // definition of the class. Thus, in any
10941 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010942 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010943 // used to refer to a union (clause 9), and either the class or
10944 // struct class-key shall be used to refer to a class (clause 9)
10945 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010946 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010947 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010948 if (OldTag == NewTag)
10949 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010950
Joao Matosdc86f942012-08-31 18:45:21 +000010951 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010952 // Warn about the struct/class tag mismatch.
10953 bool isTemplate = false;
10954 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10955 isTemplate = Record->getDescribedClassTemplate();
10956
Richard Trieucaa33d32011-06-10 03:11:26 +000010957 if (!ActiveTemplateInstantiations.empty()) {
10958 // In a template instantiation, do not offer fix-its for tag mismatches
10959 // since they usually mess up the template instead of fixing the problem.
10960 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010961 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10962 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010963 return true;
10964 }
10965
10966 if (isDefinition) {
10967 // On definitions, check previous tags and issue a fix-it for each
10968 // one that doesn't match the current tag.
10969 if (Previous->getDefinition()) {
10970 // Don't suggest fix-its for redefinitions.
10971 return true;
10972 }
10973
10974 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010975 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010976 if (I->getTagKind() != NewTag) {
10977 if (!previousMismatch) {
10978 previousMismatch = true;
10979 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010980 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10981 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010982 }
10983 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010984 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010985 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010986 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010987 }
10988 }
10989 return true;
10990 }
10991
10992 // Check for a previous definition. If current tag and definition
10993 // are same type, do nothing. If no definition, but disagree with
10994 // with previous tag type, give a warning, but no fix-it.
10995 const TagDecl *Redecl = Previous->getDefinition() ?
10996 Previous->getDefinition() : Previous;
10997 if (Redecl->getTagKind() == NewTag) {
10998 return true;
10999 }
11000
Douglas Gregord9034f02009-05-14 16:41:31 +000011001 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000011002 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11003 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000011004 Diag(Redecl->getLocation(), diag::note_previous_use);
11005
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011006 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000011007 if (Previous->getDefinition()) {
11008 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000011009 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000011010 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000011011 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000011012 }
11013
Douglas Gregord9034f02009-05-14 16:41:31 +000011014 return true;
11015 }
11016 return false;
11017}
11018
Reid Kleckner0902a512014-07-10 23:44:52 +000011019/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11020/// from an outer enclosing namespace or file scope inside a friend declaration.
11021/// This should provide the commented out code in the following snippet:
11022/// namespace N {
11023/// struct X;
11024/// namespace M {
11025/// struct Y { friend struct /*N::*/ X; };
11026/// }
11027/// }
Reid Kleckner675d4382014-07-11 00:16:51 +000011028static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11029 SourceLocation NameLoc) {
Reid Kleckner0902a512014-07-10 23:44:52 +000011030 // While the decl is in a namespace, do repeated lookup of that name and see
11031 // if we get the same namespace back. If we do not, continue until
11032 // translation unit scope, at which point we have a fully qualified NNS.
11033 SmallVector<IdentifierInfo *, 4> Namespaces;
11034 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11035 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11036 // This tag should be declared in a namespace, which can only be enclosed by
11037 // other namespaces. Bail if there's an anonymous namespace in the chain.
11038 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11039 if (!Namespace || Namespace->isAnonymousNamespace())
Reid Kleckner675d4382014-07-11 00:16:51 +000011040 return FixItHint();
Reid Kleckner0902a512014-07-10 23:44:52 +000011041 IdentifierInfo *II = Namespace->getIdentifier();
11042 Namespaces.push_back(II);
11043 NamedDecl *Lookup = SemaRef.LookupSingleName(
11044 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11045 if (Lookup == Namespace)
11046 break;
11047 }
11048
11049 // Once we have all the namespaces, reverse them to go outermost first, and
11050 // build an NNS.
11051 SmallString<64> Insertion;
11052 llvm::raw_svector_ostream OS(Insertion);
11053 if (DC->isTranslationUnit())
11054 OS << "::";
11055 std::reverse(Namespaces.begin(), Namespaces.end());
11056 for (auto *II : Namespaces)
11057 OS << II->getName() << "::";
11058 OS.flush();
Reid Kleckner675d4382014-07-11 00:16:51 +000011059 return FixItHint::CreateInsertion(NameLoc, Insertion);
Reid Kleckner0902a512014-07-10 23:44:52 +000011060}
11061
Steve Naroff30d242c2007-09-15 18:49:24 +000011062/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000011063/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000011064/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000011065/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000011066///
11067/// IsTypeSpecifier is true if this is a type-specifier (or
11068/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000011069Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000011070 SourceLocation KWLoc, CXXScopeSpec &SS,
11071 IdentifierInfo *Name, SourceLocation NameLoc,
11072 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000011073 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000011074 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000011075 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011076 SourceLocation ScopedEnumKWLoc,
11077 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000011078 TypeResult UnderlyingType,
11079 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011080 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011081 IdentifierInfo *OrigName = Name;
Craig Topperc3ec1492014-05-26 06:22:03 +000011082 assert((Name != nullptr || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000011083 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000011084 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011085
Douglas Gregord6ab8742009-05-28 23:31:59 +000011086 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000011087 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000011088 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000011089
Douglas Gregor5c0405d2009-10-07 22:35:40 +000011090 // FIXME: Check explicit specializations more carefully.
11091 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000011092 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000011093
11094 // We only need to do this matching if we have template parameters
11095 // or a scope specifier, which also conveniently avoids this work
11096 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000011097 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000011098 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011099 if (TemplateParameterList *TemplateParams =
11100 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011101 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
Richard Smith4b55a9c2014-04-17 03:29:33 +000011102 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000011103 if (Kind == TTK_Enum) {
11104 Diag(KWLoc, diag::err_enum_template);
Craig Topperc3ec1492014-05-26 06:22:03 +000011105 return nullptr;
Richard Smith1d4b2e12013-04-01 21:43:41 +000011106 }
11107
Douglas Gregor3dad8422009-09-26 06:47:28 +000011108 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000011109 // This is a declaration or definition of a class template (which may
11110 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000011111
Douglas Gregor5f0e2522010-07-14 23:14:12 +000011112 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011113 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011114
Douglas Gregore93e46c2009-07-22 23:48:44 +000011115 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000011116 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000011117 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011118 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000011119 ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011120 /*FriendLoc*/SourceLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011121 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011122 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000011123 return Result.get();
11124 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011125 // The "template<>" header is extraneous.
11126 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000011127 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011128 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000011129 }
Mike Stump11289f42009-09-09 15:08:12 +000011130 }
11131 }
11132
Douglas Gregor0bf31402010-10-08 23:50:27 +000011133 // Figure out the underlying type if this a enum declaration. We need to do
11134 // this early, because it's needed to detect if this is an incompatible
11135 // redeclaration.
11136 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11137
11138 if (Kind == TTK_Enum) {
11139 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11140 // No underlying type explicitly specified, or we failed to parse the
11141 // type, default to int.
11142 EnumUnderlying = Context.IntTy.getTypePtr();
11143 else if (UnderlyingType.get()) {
11144 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11145 // integral type; any cv-qualification is ignored.
Craig Topperc3ec1492014-05-26 06:22:03 +000011146 TypeSourceInfo *TI = nullptr;
Richard Smitheece8c32012-03-15 00:22:18 +000011147 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011148 EnumUnderlying = TI;
11149
Richard Smith4b38ded2012-03-14 23:13:10 +000011150 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000011151 // Recover by falling back to int.
11152 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000011153
Richard Smith4b38ded2012-03-14 23:13:10 +000011154 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000011155 UPPC_FixedUnderlyingType))
11156 EnumUnderlying = Context.IntTy.getTypePtr();
11157
Alp Tokerbfa39342014-01-14 12:51:41 +000011158 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000011159 // Microsoft enums are always of int type.
11160 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000011161 }
11162
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011163 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000011164 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000011165 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000011166
Chandler Carrutha419dbb2010-03-01 21:17:36 +000011167 RedeclarationKind Redecl = ForRedeclaration;
11168 if (TUK == TUK_Friend || TUK == TUK_Reference)
11169 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000011170
11171 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000011172 if (Name && SS.isNotEmpty()) {
11173 // We have a nested-name tag ('struct foo::bar').
11174
11175 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000011176 if (SS.isInvalid()) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011177 Name = nullptr;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000011178 goto CreateNewDecl;
11179 }
11180
John McCall7f41d982009-09-11 04:59:25 +000011181 // If this is a friend or a reference to a class in a dependent
11182 // context, don't try to make a decl for it.
11183 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11184 DC = computeDeclContext(SS, false);
11185 if (!DC) {
11186 IsDependent = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000011187 return nullptr;
John McCall7f41d982009-09-11 04:59:25 +000011188 }
John McCall0b66eb32010-05-01 00:40:08 +000011189 } else {
11190 DC = computeDeclContext(SS, true);
11191 if (!DC) {
11192 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11193 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011194 return nullptr;
John McCall0b66eb32010-05-01 00:40:08 +000011195 }
John McCall7f41d982009-09-11 04:59:25 +000011196 }
11197
John McCall0b66eb32010-05-01 00:40:08 +000011198 if (RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +000011199 return nullptr;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000011200
Douglas Gregor8761da52009-02-03 00:34:39 +000011201 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000011202 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000011203 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000011204
John McCall1f82f242009-11-18 22:49:29 +000011205 if (Previous.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000011206 return nullptr;
John McCall6538c932009-10-10 05:48:19 +000011207
John McCall1f82f242009-11-18 22:49:29 +000011208 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000011209 // Name lookup did not find anything. However, if the
11210 // nested-name-specifier refers to the current instantiation,
11211 // and that current instantiation has any dependent base
11212 // classes, we might find something at instantiation time: treat
11213 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000011214 // But this only makes any sense for reference-like lookups.
11215 if (Previous.wasNotFoundInCurrentInstantiation() &&
11216 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000011217 IsDependent = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000011218 return nullptr;
Douglas Gregord2e6a452010-01-14 17:47:39 +000011219 }
11220
11221 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000011222 Diag(NameLoc, diag::err_not_tag_in_scope)
11223 << Kind << Name << DC << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011224 Name = nullptr;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011225 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000011226 goto CreateNewDecl;
11227 }
Chris Lattnerd9773512009-01-21 02:38:50 +000011228 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000011229 // If this is a named struct, check to see if there was a previous forward
11230 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000011231 // FIXME: We're looking into outer scopes here, even when we
11232 // shouldn't be. Doing so can result in ambiguities that we
11233 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000011234 LookupName(Previous, S);
11235
John McCall3c581bf2013-03-20 01:53:00 +000011236 // When declaring or defining a tag, ignore ambiguities introduced
11237 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000011238 if (Previous.isAmbiguous() &&
11239 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000011240 LookupResult::Filter F = Previous.makeFilter();
11241 while (F.hasNext()) {
11242 NamedDecl *ND = F.next();
11243 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11244 F.erase();
11245 }
11246 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000011247 }
John McCall3c581bf2013-03-20 01:53:00 +000011248
11249 // C++11 [namespace.memdef]p3:
11250 // If the name in a friend declaration is neither qualified nor
11251 // a template-id and the declaration is a function or an
11252 // elaborated-type-specifier, the lookup to determine whether
11253 // the entity has been previously declared shall not consider
11254 // any scopes outside the innermost enclosing namespace.
11255 //
Reid Kleckner0902a512014-07-10 23:44:52 +000011256 // MSVC doesn't implement the above rule for types, so a friend tag
11257 // declaration may be a redeclaration of a type declared in an enclosing
11258 // scope. They do implement this rule for friend functions.
11259 //
John McCall3c581bf2013-03-20 01:53:00 +000011260 // Does it matter that this should be by scope instead of by
11261 // semantic context?
11262 if (!Previous.empty() && TUK == TUK_Friend) {
11263 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11264 LookupResult::Filter F = Previous.makeFilter();
Reid Kleckner0902a512014-07-10 23:44:52 +000011265 bool FriendSawTagOutsideEnclosingNamespace = false;
John McCall3c581bf2013-03-20 01:53:00 +000011266 while (F.hasNext()) {
11267 NamedDecl *ND = F.next();
11268 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000011269 if (DC->isFileContext() &&
11270 !EnclosingNS->Encloses(ND->getDeclContext())) {
Reid Kleckner0902a512014-07-10 23:44:52 +000011271 if (getLangOpts().MSVCCompat)
11272 FriendSawTagOutsideEnclosingNamespace = true;
11273 else
11274 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000011275 }
John McCall3c581bf2013-03-20 01:53:00 +000011276 }
11277 F.done();
Reid Kleckner0902a512014-07-10 23:44:52 +000011278
11279 // Diagnose this MSVC extension in the easy case where lookup would have
11280 // unambiguously found something outside the enclosing namespace.
11281 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11282 NamedDecl *ND = Previous.getFoundDecl();
Reid Kleckner675d4382014-07-11 00:16:51 +000011283 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11284 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
Reid Kleckner0902a512014-07-10 23:44:52 +000011285 }
John McCall3c581bf2013-03-20 01:53:00 +000011286 }
Reid Kleckner0902a512014-07-10 23:44:52 +000011287
John McCall1f82f242009-11-18 22:49:29 +000011288 // Note: there used to be some attempt at recovery here.
11289 if (Previous.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000011290 return nullptr;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011291
David Blaikiebbafb8a2012-03-11 07:00:24 +000011292 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011293 // FIXME: This makes sure that we ignore the contexts associated
11294 // with C structs, unions, and enums when looking for a matching
11295 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000011296 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011297 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11298 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011299 }
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000011300 }
11301
John McCall1f82f242009-11-18 22:49:29 +000011302 if (Previous.isSingleResult() &&
11303 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000011304 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000011305 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000011306 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000011307 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000011308 }
11309
David Blaikiebbafb8a2012-03-11 07:00:24 +000011310 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011311 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000011312 // This is a declaration of or a reference to "std::bad_alloc".
11313 isStdBadAlloc = true;
11314
John McCall1f82f242009-11-18 22:49:29 +000011315 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000011316 // std::bad_alloc has been implicitly declared (but made invisible to
11317 // name lookup). Fill in this implicit declaration as the previous
11318 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011319 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000011320 }
11321 }
John McCall1f82f242009-11-18 22:49:29 +000011322
John McCalle9eaf8e2010-03-25 21:28:06 +000011323 // If we didn't find a previous declaration, and this is a reference
11324 // (or friend reference), move to the correct scope. In C++, we
11325 // also need to do a redeclaration lookup there, just in case
11326 // there's a shadow friend decl.
11327 if (Name && Previous.empty() &&
11328 (TUK == TUK_Reference || TUK == TUK_Friend)) {
11329 if (Invalid) goto CreateNewDecl;
11330 assert(SS.isEmpty());
11331
11332 if (TUK == TUK_Reference) {
11333 // C++ [basic.scope.pdecl]p5:
11334 // -- for an elaborated-type-specifier of the form
11335 //
11336 // class-key identifier
11337 //
11338 // if the elaborated-type-specifier is used in the
11339 // decl-specifier-seq or parameter-declaration-clause of a
11340 // function defined in namespace scope, the identifier is
11341 // declared as a class-name in the namespace that contains
11342 // the declaration; otherwise, except as a friend
11343 // declaration, the identifier is declared in the smallest
11344 // non-class, non-function-prototype scope that contains the
11345 // declaration.
11346 //
11347 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11348 // C structs and unions.
11349 //
11350 // It is an error in C++ to declare (rather than define) an enum
11351 // type, including via an elaborated type specifier. We'll
11352 // diagnose that later; for now, declare the enum in the same
11353 // scope as we would have picked for any other tag type.
11354 //
11355 // GNU C also supports this behavior as part of its incomplete
11356 // enum types extension, while GNU C++ does not.
11357 //
11358 // Find the context where we'll be declaring the tag.
11359 // FIXME: We would like to maintain the current DeclContext as the
11360 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000011361 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000011362 SearchDC = SearchDC->getParent();
11363
11364 // Find the scope where we'll be declaring the tag.
11365 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011366 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000011367 S->isFunctionPrototypeScope()) ||
11368 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000011369 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000011370 S = S->getParent();
11371 } else {
11372 assert(TUK == TUK_Friend);
11373 // C++ [namespace.memdef]p3:
11374 // If a friend declaration in a non-local class first declares a
11375 // class or function, the friend class or function is a member of
11376 // the innermost enclosing namespace.
11377 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000011378 }
11379
John McCalle87beb22010-04-23 18:46:30 +000011380 // In C++, we need to do a redeclaration lookup to properly
11381 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011382 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000011383 Previous.setRedeclarationKind(ForRedeclaration);
11384 LookupQualifiedName(Previous, SearchDC);
11385 }
11386 }
11387
John McCall1f82f242009-11-18 22:49:29 +000011388 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000011389 NamedDecl *PrevDecl = Previous.getFoundDecl();
11390 NamedDecl *DirectPrevDecl =
11391 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000011392
11393 // It's okay to have a tag decl in the same scope as a typedef
11394 // which hides a tag decl in the same scope. Finding this
11395 // insanity with a redeclaration lookup can only actually happen
11396 // in C++.
11397 //
11398 // This is also okay for elaborated-type-specifiers, which is
11399 // technically forbidden by the current standard but which is
11400 // okay according to the likely resolution of an open issue;
11401 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000011402 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000011403 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000011404 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11405 TagDecl *Tag = TT->getDecl();
11406 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011407 Tag->getDeclContext()->getRedeclContext()
11408 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000011409 PrevDecl = Tag;
11410 Previous.clear();
11411 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000011412 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000011413 }
11414 }
11415 }
11416 }
11417
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011418 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000011419 // If this is a use of a previous tag, or if the tag is already declared
11420 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011421 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000011422 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000011423 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000011424 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000011425 // Make sure that this wasn't declared as an enum and now used as a
11426 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000011427 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11428 TUK == TUK_Definition, KWLoc,
11429 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000011430 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000011431 = (PrevTagDecl->getTagKind() != TTK_Enum &&
11432 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000011433 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000011434 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000011435 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000011436 << FixItHint::CreateReplacement(SourceRange(KWLoc),
11437 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000011438 else
11439 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000011440 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000011441
Mike Stump11289f42009-09-09 15:08:12 +000011442 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000011443 Kind = PrevTagDecl->getTagKind();
11444 else {
11445 // Recover by making this an anonymous redefinition.
Craig Topperc3ec1492014-05-26 06:22:03 +000011446 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011447 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000011448 Invalid = true;
11449 }
11450 }
11451
Douglas Gregor0bf31402010-10-08 23:50:27 +000011452 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11453 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11454
Richard Smith0f8ee222012-01-10 01:33:14 +000011455 // If this is an elaborated-type-specifier for a scoped enumeration,
11456 // the 'class' keyword is not necessary and not permitted.
11457 if (TUK == TUK_Reference || TUK == TUK_Friend) {
11458 if (ScopedEnum)
11459 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11460 << PrevEnum->isScoped()
11461 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11462 return PrevTagDecl;
11463 }
11464
Richard Smith4b38ded2012-03-14 23:13:10 +000011465 QualType EnumUnderlyingTy;
11466 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000011467 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000011468 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11469 EnumUnderlyingTy = QualType(T, 0);
11470
Douglas Gregor0bf31402010-10-08 23:50:27 +000011471 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000011472 // returning the previous declaration, unless this is a definition,
11473 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000011474 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11475 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Craig Topperc3ec1492014-05-26 06:22:03 +000011476 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
Douglas Gregor0bf31402010-10-08 23:50:27 +000011477 }
11478
David Majnemer55890bf2013-06-11 03:51:23 +000011479 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000011480 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000011481 // except that a nested class or member class template can be declared
11482 // and then later defined.
11483 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11484 S->isDeclScope(PrevDecl)) {
11485 Diag(NameLoc, diag::ext_member_redeclared);
11486 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11487 }
11488
Douglas Gregor170512f2009-04-01 23:51:29 +000011489 if (!Invalid) {
John McCall2976f8b2014-05-14 07:54:17 +000011490 // If this is a use, just return the declaration we found, unless
11491 // we have attributes.
Chris Lattner9ff58d72008-07-03 03:30:58 +000011492
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011493 // FIXME: In the future, return a variant or some other clue
11494 // for the consumer of this Decl to know it doesn't own it.
11495 // For our current ASTs this shouldn't be a problem, but will
11496 // need to be changed with DeclGroups.
John McCall2976f8b2014-05-14 07:54:17 +000011497 if (!Attr &&
11498 ((TUK == TUK_Reference &&
11499 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11500 || TUK == TUK_Friend))
John McCall48871652010-08-21 09:40:31 +000011501 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011502
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011503 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000011504 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000011505 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000011506 // If we're defining a specialization and the previous definition
11507 // is from an implicit instantiation, don't emit an error
11508 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000011509 bool IsExplicitSpecializationAfterInstantiation = false;
11510 if (isExplicitSpecialization) {
11511 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11512 IsExplicitSpecializationAfterInstantiation =
11513 RD->getTemplateSpecializationKind() !=
11514 TSK_ExplicitSpecialization;
11515 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11516 IsExplicitSpecializationAfterInstantiation =
11517 ED->getTemplateSpecializationKind() !=
11518 TSK_ExplicitSpecialization;
11519 }
11520
11521 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000011522 // A redeclaration in function prototype scope in C isn't
11523 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011524 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000011525 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11526 else
11527 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000011528 Diag(Def->getLocation(), diag::note_previous_definition);
11529 // If this is a redefinition, recover by making this
11530 // struct be anonymous, which will make any later
11531 // references get the previous definition.
Craig Topperc3ec1492014-05-26 06:22:03 +000011532 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011533 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000011534 Invalid = true;
11535 }
Douglas Gregordee1be82009-01-17 00:42:38 +000011536 } else {
11537 // If the type is currently being defined, complain
11538 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000011539 const TagType *Tag
11540 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000011541 if (Tag->isBeingDefined()) {
11542 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000011543 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000011544 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000011545 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011546 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000011547 Invalid = true;
11548 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011549 }
Douglas Gregordee1be82009-01-17 00:42:38 +000011550
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011551 // Okay, this is definition of a previously declared or referenced
John McCalla16fc892014-05-14 18:31:48 +000011552 // tag. We're going to create a new Decl for it.
11553 }
11554
11555 // Okay, we're going to make a redeclaration. If this is some kind
11556 // of reference, make sure we build the redeclaration in the same DC
11557 // as the original, and ignore the current access specifier.
11558 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11559 SearchDC = PrevTagDecl->getDeclContext();
11560 AS = AS_none;
Douglas Gregordee1be82009-01-17 00:42:38 +000011561 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011562 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011563 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000011564 // have a definition. Just create a new decl.
11565
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011566 } else {
11567 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000011568 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011569 // new decl/type. We set PrevDecl to NULL so that the entities
11570 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000011571 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000011572 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011573 // If we get here, we're going to create a new Decl. If PrevDecl
11574 // is non-NULL, it's a definition of the tag declared by
11575 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000011576
11577
11578 // Otherwise, PrevDecl is not a tag, but was found with tag
11579 // lookup. This is only actually possible in C++, where a few
11580 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011581 } else {
John McCalle87beb22010-04-23 18:46:30 +000011582 // Use a better diagnostic if an elaborated-type-specifier
11583 // found the wrong kind of type on the first
11584 // (non-redeclaration) lookup.
11585 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11586 !Previous.isForRedeclaration()) {
11587 unsigned Kind = 0;
11588 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011589 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11590 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011591 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11592 Diag(PrevDecl->getLocation(), diag::note_declared_at);
11593 Invalid = true;
11594
11595 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000011596 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11597 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000011598 // do nothing
11599
11600 // Diagnose implicit declarations introduced by elaborated types.
11601 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11602 unsigned Kind = 0;
11603 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011604 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11605 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011606 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11607 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11608 Invalid = true;
11609
11610 // Otherwise it's a declaration. Call out a particularly common
11611 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000011612 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11613 unsigned Kind = 0;
11614 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000011615 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000011616 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000011617 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11618 Invalid = true;
11619
11620 // Otherwise, diagnose.
11621 } else {
11622 // The tag name clashes with something else in the target scope,
11623 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000011624 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000011625 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000011626 Name = nullptr;
Douglas Gregordee1be82009-01-17 00:42:38 +000011627 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011628 }
John McCalle87beb22010-04-23 18:46:30 +000011629
11630 // The existing declaration isn't relevant to us; we're in a
11631 // new scope, so clear out the previous declaration.
11632 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000011633 }
Chris Lattner18b19622007-01-22 07:39:13 +000011634 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000011635
Chris Lattner438e5012008-12-17 07:13:27 +000011636CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000011637
Craig Topperc3ec1492014-05-26 06:22:03 +000011638 TagDecl *PrevDecl = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011639 if (Previous.isSingleResult())
11640 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11641
Chris Lattnerbf0b7982007-01-23 04:27:41 +000011642 // If there is an identifier, use the location of the identifier as the
11643 // location of the decl, otherwise use the location of the struct/union
11644 // keyword.
11645 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000011646
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011647 // Otherwise, create a new declaration. If there is a previous
11648 // declaration of the same entity, the two will be linked via
11649 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000011650 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000011651
Douglas Gregor0bf31402010-10-08 23:50:27 +000011652 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000011653 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000011654 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11655 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011656 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000011657 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000011658 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000011659 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011660 if (TUK != TUK_Definition && !Invalid) {
11661 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000011662 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11663 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000011664 // C++0x: 7.2p2: opaque-enum-declaration.
11665 // Conflicts are diagnosed above. Do nothing.
11666 }
11667 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011668 Diag(Loc, diag::ext_forward_ref_enum_def)
11669 << New;
11670 Diag(Def->getLocation(), diag::note_previous_definition);
11671 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000011672 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000011673 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000011674 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011675 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000011676 DiagID = diag::err_forward_ref_enum;
11677 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011678
11679 // If this is a forward-declared reference to an enumeration, make a
11680 // note of it; we won't actually be introducing the declaration into
11681 // the declaration context.
11682 if (TUK == TUK_Reference)
11683 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011684 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000011685 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000011686
11687 if (EnumUnderlying) {
11688 EnumDecl *ED = cast<EnumDecl>(New);
11689 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11690 ED->setIntegerTypeSourceInfo(TI);
11691 else
11692 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11693 ED->setPromotionType(ED->getIntegerType());
11694 }
11695
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011696 } else {
11697 // struct/union/class
11698
Chris Lattner776fac82007-06-09 00:53:06 +000011699 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11700 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011701 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000011702 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011703 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011704 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011705
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011706 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000011707 StdBadAlloc = cast<CXXRecordDecl>(New);
11708 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011709 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011710 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011711 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011712
Richard Smith649c7b062014-01-08 00:56:48 +000011713 // C++11 [dcl.type]p3:
11714 // A type-specifier-seq shall not define a class or enumeration [...].
11715 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11716 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11717 << Context.getTagDeclType(New);
11718 Invalid = true;
11719 }
11720
John McCall3e11ebe2010-03-15 10:12:16 +000011721 // Maybe add qualifier info.
11722 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011723 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011724 // If this is either a declaration or a definition, check the
11725 // nested-name-specifier against the current context. We don't do this
11726 // for explicit specializations, because they have similar checking
11727 // (with more specific diagnostics) in the call to
11728 // CheckMemberSpecialization, below.
11729 if (!isExplicitSpecialization &&
11730 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11731 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11732 Invalid = true;
11733
Douglas Gregor14454802011-02-25 02:25:35 +000011734 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011735 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011736 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011737 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011738 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011739 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011740 }
11741 else
11742 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011743 }
11744
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011745 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11746 // Add alignment attributes if necessary; these attributes are checked when
11747 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011748 //
11749 // It is important for implementing the correct semantics that this
11750 // happen here (in act on tag decl). The #pragma pack stack is
11751 // maintained as a result of parser callbacks which can occur at
11752 // many points during the parsing of a struct declaration (because
11753 // the #pragma tokens are effectively skipped over during the
11754 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011755 if (TUK == TUK_Definition) {
11756 AddAlignmentAttributesForRecord(RD);
11757 AddMsStructLayoutForRecord(RD);
11758 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011759 }
11760
Douglas Gregor21823bf2011-12-20 18:11:52 +000011761 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011762 if (isExplicitSpecialization)
11763 Diag(New->getLocation(), diag::err_module_private_specialization)
11764 << 2
11765 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011766 // __module_private__ does not apply to local classes. However, we only
11767 // diagnose this as an error when the declaration specifiers are
11768 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011769 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011770 New->setModulePrivate();
11771 }
Serge Pavlova8261472014-06-25 17:09:41 +000011772
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011773 // If this is a specialization of a member class (of a class template),
11774 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011775 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011776 Invalid = true;
Serge Pavlova8261472014-06-25 17:09:41 +000011777
11778 // If we're declaring or defining a tag in function prototype scope in C,
11779 // note that this type can only be used within the function and add it to
11780 // the list of decls to inject into the function definition scope.
11781 if ((Name || Kind == TTK_Enum) &&
11782 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11783 if (getLangOpts().CPlusPlus) {
11784 // C++ [dcl.fct]p6:
11785 // Types shall not be defined in return or parameter types.
11786 if (TUK == TUK_Definition && !IsTypeSpecifier) {
11787 Diag(Loc, diag::err_type_defined_in_param_type)
11788 << Name;
11789 Invalid = true;
11790 }
11791 } else {
11792 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11793 }
11794 DeclsInPrototypeScope.push_back(New);
11795 }
11796
Douglas Gregordee1be82009-01-17 00:42:38 +000011797 if (Invalid)
11798 New->setInvalidDecl();
11799
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011800 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011801 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011802
11803 // Set the lexical context. If the tag has a C++ scope specifier, the
11804 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011805 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011806
John McCallaa74a0c2009-08-28 07:59:38 +000011807 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011808 // In Microsoft mode, a friend declaration also acts as a forward
11809 // declaration so we always pass true to setObjectOfFriendDecl to make
11810 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011811 if (TUK == TUK_Friend)
Reid Kleckner0902a512014-07-10 23:44:52 +000011812 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
John McCallaa74a0c2009-08-28 07:59:38 +000011813
Anders Carlsson5558ca12009-03-26 01:19:02 +000011814 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011815 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011816 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011817
John McCall9bb74a52009-07-31 02:45:11 +000011818 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011819 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011820
Chris Lattner18b19622007-01-22 07:39:13 +000011821 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011822 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011823 // We might be replacing an existing declaration in the lookup tables;
11824 // if so, borrow its access specifier.
11825 if (PrevDecl)
11826 New->setAccess(PrevDecl->getAccess());
11827
Sebastian Redl50c68252010-08-31 00:36:30 +000011828 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011829 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011830 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011831 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11832 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011833 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011834 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011835 PushOnScopeChains(New, S, !IsForwardReference);
11836 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011837 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011838
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011839 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011840 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011841 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011842
Douglas Gregor27821ce2009-07-07 16:35:42 +000011843 // If this is the C FILE type, notify the AST context.
11844 if (IdentifierInfo *II = New->getIdentifier())
11845 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011846 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011847 II->isStr("FILE"))
11848 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011849
Rafael Espindolac67f2232012-05-10 02:50:16 +000011850 if (PrevDecl)
11851 mergeDeclAttributes(New, PrevDecl);
11852
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011853 // If there's a #pragma GCC visibility in scope, set the visibility of this
11854 // record.
11855 AddPushedVisibilityAttribute(New);
11856
Douglas Gregord6ab8742009-05-28 23:31:59 +000011857 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011858 // In C++, don't return an invalid declaration. We can't recover well from
11859 // the cases where we make the type anonymous.
Craig Topperc3ec1492014-05-26 06:22:03 +000011860 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011861}
Chris Lattner1300fb92007-01-23 23:42:53 +000011862
John McCall48871652010-08-21 09:40:31 +000011863void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011864 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011865 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011866
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011867 // Enter the tag context.
11868 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011869
11870 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011871
11872 // If there's a #pragma GCC visibility in scope, set the visibility of this
11873 // record.
11874 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011875}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011876
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011877Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011878 assert(isa<ObjCContainerDecl>(IDecl) &&
11879 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11880 DeclContext *OCD = cast<DeclContext>(IDecl);
11881 assert(getContainingDC(OCD) == CurContext &&
11882 "The next DeclContext should be lexically contained in the current one.");
11883 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011884 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011885}
11886
John McCall48871652010-08-21 09:40:31 +000011887void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011888 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011889 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011890 SourceLocation LBraceLoc) {
11891 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011892 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011893
John McCall1c7e6ec2009-12-20 07:58:13 +000011894 FieldCollector->StartClass();
11895
11896 if (!Record->getIdentifier())
11897 return;
11898
Anders Carlsson30f29442011-03-25 14:31:08 +000011899 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011900 Record->addAttr(new (Context)
11901 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11902
John McCall1c7e6ec2009-12-20 07:58:13 +000011903 // C++ [class]p2:
11904 // [...] The class-name is also inserted into the scope of the
11905 // class itself; this is known as the injected-class-name. For
11906 // purposes of access checking, the injected-class-name is treated
11907 // as if it were a public member name.
11908 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011909 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11910 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011911 Record->getIdentifier(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011912 /*PrevDecl=*/nullptr,
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011913 /*DelayTypeCreation=*/true);
11914 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011915 InjectedClassName->setImplicit();
11916 InjectedClassName->setAccess(AS_public);
11917 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11918 InjectedClassName->setDescribedClassTemplate(Template);
11919 PushOnScopeChains(InjectedClassName, S);
11920 assert(InjectedClassName->isInjectedClassName() &&
11921 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011922}
11923
John McCall48871652010-08-21 09:40:31 +000011924void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011925 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011926 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011927 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011928 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011929
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011930 // Make sure we "complete" the definition even it is invalid.
11931 if (Tag->isBeingDefined()) {
11932 assert(Tag->isInvalidDecl() && "We should already have completed it");
11933 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11934 RD->completeDefinition();
11935 }
11936
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011937 if (isa<CXXRecordDecl>(Tag))
11938 FieldCollector->FinishClass();
11939
11940 // Exit this scope of this tag's definition.
11941 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011942
11943 if (getCurLexicalContext()->isObjCContainer() &&
11944 Tag->getDeclContext()->isFileContext())
11945 Tag->setTopLevelDeclInObjCContainer();
11946
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011947 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011948 if (!Tag->isInvalidDecl())
11949 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011950}
Chris Lattner535b8302008-06-21 19:39:06 +000011951
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011952void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011953 // Exit this scope of this interface definition.
11954 PopDeclContext();
11955}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011956
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011957void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011958 assert(DC == CurContext && "Mismatch of container contexts");
11959 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011960 ActOnObjCContainerFinishDefinition();
11961}
11962
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011963void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11964 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Craig Topperc3ec1492014-05-26 06:22:03 +000011965 OriginalLexicalContext = nullptr;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011966}
11967
John McCall48871652010-08-21 09:40:31 +000011968void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011969 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011970 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011971 Tag->setInvalidDecl();
11972
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011973 // Make sure we "complete" the definition even it is invalid.
11974 if (Tag->isBeingDefined()) {
11975 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11976 RD->completeDefinition();
11977 }
11978
John McCall71ba5f22010-03-17 19:25:57 +000011979 // We're undoing ActOnTagStartDefinition here, not
11980 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11981 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011982
11983 PopDeclContext();
11984}
11985
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011986// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011987ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11988 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011989 QualType FieldTy, bool IsMsStruct,
11990 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011991 // Default to true; that shouldn't confuse checks for emptiness
11992 if (ZeroWidth)
11993 *ZeroWidth = true;
11994
Chris Lattner73bf7b42009-03-05 22:45:59 +000011995 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011996 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011997 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011998 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011999 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000012000 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000012001 if (FieldName)
12002 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12003 << FieldName << FieldTy << BitWidth->getSourceRange();
12004 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12005 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000012006 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12007 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000012008 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000012009
12010 // If the bit-width is type- or value-dependent, don't try to check
12011 // it now.
12012 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012013 return BitWidth;
Douglas Gregor1efa4372009-03-11 18:59:21 +000012014
Anders Carlsson5df391e2008-12-06 20:33:04 +000012015 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000012016 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12017 if (ICE.isInvalid())
12018 return ICE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012019 BitWidth = ICE.get();
Anders Carlsson5df391e2008-12-06 20:33:04 +000012020
Eli Friedmanc96d4962009-08-15 21:55:26 +000012021 if (Value != 0 && ZeroWidth)
12022 *ZeroWidth = false;
12023
Chris Lattner81ed6802008-12-12 04:56:04 +000012024 // Zero-width bitfield is ok for anonymous field.
12025 if (Value == 0 && FieldName)
12026 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000012027
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000012028 if (Value.isSigned() && Value.isNegative()) {
12029 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000012030 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000012031 << FieldName << Value.toString(10);
12032 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12033 << Value.toString(10);
12034 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000012035
Douglas Gregor1efa4372009-03-11 18:59:21 +000012036 if (!FieldTy->isDependentType()) {
12037 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000012038 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000012039 if (!getLangOpts().CPlusPlus || IsMsStruct ||
12040 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000012041 if (FieldName)
12042 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12043 << FieldName << (unsigned)Value.getZExtValue()
12044 << (unsigned)TypeSize;
12045
12046 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12047 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12048 }
12049
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000012050 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000012051 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12052 << FieldName << (unsigned)Value.getZExtValue()
12053 << (unsigned)TypeSize;
12054 else
12055 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12056 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000012057 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000012058 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000012059
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012060 return BitWidth;
Anders Carlsson5df391e2008-12-06 20:33:04 +000012061}
12062
Richard Smith938f40b2011-06-11 17:19:42 +000012063/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000012064/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000012065Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000012066 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000012067 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000012068 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000012069 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000012070 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000012071}
12072
12073/// HandleField - Analyze a field of a C struct or a C++ data member.
12074///
12075FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12076 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000012077 Declarator &D, Expr *BitWidth,
12078 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000012079 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000012080 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000012081 SourceLocation Loc = DeclStart;
12082 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000012083
John McCall8cb7bdf2010-06-04 23:28:52 +000012084 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12085 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012086 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000012087 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000012088
Douglas Gregora02a72a2010-12-15 23:18:36 +000012089 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12090 UPPC_DataMemberType)) {
12091 D.setInvalidType();
12092 T = Context.IntTy;
12093 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12094 }
12095 }
12096
Matt Arsenault376f7202013-02-26 21:16:00 +000012097 // TR 18037 does not allow fields to be declared with address spaces.
12098 if (T.getQualifiers().hasAddressSpace()) {
12099 Diag(Loc, diag::err_field_with_address_space);
12100 D.setInvalidType();
12101 }
12102
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000012103 // OpenCL 1.2 spec, s6.9 r:
12104 // The event type cannot be used to declare a structure or union field.
12105 if (LangOpts.OpenCL && T->isEventT()) {
12106 Diag(Loc, diag::err_event_t_struct_field);
12107 D.setInvalidType();
12108 }
12109
Richard Smithb1402ae2013-03-18 22:52:47 +000012110 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000012111
Richard Smithb4a9e862013-04-12 22:46:28 +000012112 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12113 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12114 diag::err_invalid_thread)
12115 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000012116
Douglas Gregor2c7d9292010-08-30 14:32:14 +000012117 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000012118 NamedDecl *PrevDecl = nullptr;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000012119 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12120 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000012121 switch (Previous.getResultKind()) {
12122 case LookupResult::Found:
12123 case LookupResult::FoundUnresolvedValue:
12124 PrevDecl = Previous.getAsSingle<NamedDecl>();
12125 break;
12126
12127 case LookupResult::FoundOverloaded:
12128 PrevDecl = Previous.getRepresentativeDecl();
12129 break;
12130
12131 case LookupResult::NotFound:
12132 case LookupResult::NotFoundInCurrentInstantiation:
12133 case LookupResult::Ambiguous:
12134 break;
12135 }
12136 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000012137
12138 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12139 // Maybe we will complain about the shadowed template parameter.
12140 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12141 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012142 PrevDecl = nullptr;
Douglas Gregorf187420f2009-06-17 23:37:01 +000012143 }
12144
Douglas Gregor1efa4372009-03-11 18:59:21 +000012145 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000012146 PrevDecl = nullptr;
Douglas Gregor1efa4372009-03-11 18:59:21 +000012147
Steve Naroff5ec6ff72009-07-14 14:58:18 +000012148 bool Mutable
12149 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012150 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000012151 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000012152 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000012153 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000012154
12155 if (NewFD->isInvalidDecl())
12156 Record->setInvalidDecl();
12157
Douglas Gregor3baa6702011-09-12 16:11:24 +000012158 if (D.getDeclSpec().isModulePrivateSpecified())
12159 NewFD->setModulePrivate();
12160
Douglas Gregor1efa4372009-03-11 18:59:21 +000012161 if (NewFD->isInvalidDecl() && PrevDecl) {
12162 // Don't introduce NewFD into scope; there's already something
12163 // with the same name in the same scope.
12164 } else if (II) {
12165 PushOnScopeChains(NewFD, S);
12166 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012167 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000012168
12169 return NewFD;
12170}
12171
12172/// \brief Build a new FieldDecl and check its well-formedness.
12173///
12174/// This routine builds a new FieldDecl given the fields name, type,
12175/// record, etc. \p PrevDecl should refer to any previous declaration
12176/// with the same name and in the same scope as the field to be
12177/// created.
12178///
12179/// \returns a new FieldDecl.
12180///
Mike Stump11289f42009-09-09 15:08:12 +000012181/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000012182FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000012183 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000012184 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000012185 bool Mutable, Expr *BitWidth,
12186 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000012187 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000012188 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000012189 Declarator *D) {
12190 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000012191 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012192 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012193
Douglas Gregor1efa4372009-03-11 18:59:21 +000012194 // If we receive a broken type, recover by assuming 'int' and
12195 // marking this declaration as invalid.
12196 if (T.isNull()) {
12197 InvalidDecl = true;
12198 T = Context.IntTy;
12199 }
12200
Eli Friedmand0e8de22009-12-07 00:22:08 +000012201 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000012202 if (!EltTy->isDependentType()) {
12203 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12204 // Fields of incomplete type force their record to be invalid.
12205 Record->setInvalidDecl();
12206 InvalidDecl = true;
12207 } else {
12208 NamedDecl *Def;
12209 EltTy->isIncompleteType(&Def);
12210 if (Def && Def->isInvalidDecl()) {
12211 Record->setInvalidDecl();
12212 InvalidDecl = true;
12213 }
12214 }
John McCall2677e102010-08-16 23:42:35 +000012215 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000012216
Joey Gouly1d58cdb2013-01-17 17:35:00 +000012217 // OpenCL v1.2 s6.9.c: bitfields are not supported.
12218 if (BitWidth && getLangOpts().OpenCL) {
12219 Diag(Loc, diag::err_opencl_bitfields);
12220 InvalidDecl = true;
12221 }
12222
Steve Naroff8eeeb132007-05-08 21:09:37 +000012223 // C99 6.7.2.1p8: A member of a structure or union may have any type other
12224 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000012225 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000012226 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000012227 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000012228
12229 TypeSourceInfo *FixedTInfo =
12230 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12231 SizeIsNegative,
12232 Oversized);
12233 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000012234 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000012235 TInfo = FixedTInfo;
12236 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000012237 } else {
12238 if (SizeIsNegative)
12239 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000012240 else if (Oversized.getBoolValue())
12241 Diag(Loc, diag::err_array_too_large)
12242 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000012243 else
12244 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000012245 InvalidDecl = true;
12246 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000012247 }
Mike Stump11289f42009-09-09 15:08:12 +000012248
Anders Carlsson576cc6f2009-03-22 20:18:17 +000012249 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000012250 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12251 diag::err_abstract_type_in_decl,
12252 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000012253 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000012254
Eli Friedmanc96d4962009-08-15 21:55:26 +000012255 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000012256 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000012257 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000012258 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012259 &ZeroWidth).get();
Richard Smithf4c51d92012-02-04 09:53:13 +000012260 if (!BitWidth) {
12261 InvalidDecl = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000012262 BitWidth = nullptr;
Richard Smithf4c51d92012-02-04 09:53:13 +000012263 ZeroWidth = false;
12264 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000012265 }
Mike Stump11289f42009-09-09 15:08:12 +000012266
John McCallb1cd7da2010-06-04 08:34:12 +000012267 // Check that 'mutable' is consistent with the type of the declaration.
12268 if (!InvalidDecl && Mutable) {
12269 unsigned DiagID = 0;
12270 if (T->isReferenceType())
12271 DiagID = diag::err_mutable_reference;
12272 else if (T.isConstQualified())
12273 DiagID = diag::err_mutable_const;
12274
12275 if (DiagID) {
12276 SourceLocation ErrLoc = Loc;
12277 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12278 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12279 Diag(ErrLoc, DiagID);
12280 Mutable = false;
12281 InvalidDecl = true;
12282 }
12283 }
12284
Richard Smithab44d5b2013-12-10 08:25:00 +000012285 // C++11 [class.union]p8 (DR1460):
12286 // At most one variant member of a union may have a
12287 // brace-or-equal-initializer.
12288 if (InitStyle != ICIS_NoInit)
12289 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12290
Abramo Bagnaradff19302011-03-08 08:55:46 +000012291 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000012292 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012293 if (InvalidDecl)
12294 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000012295
Douglas Gregor1efa4372009-03-11 18:59:21 +000012296 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12297 Diag(Loc, diag::err_duplicate_member) << II;
12298 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12299 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012300 }
12301
David Blaikiebbafb8a2012-03-11 07:00:24 +000012302 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000012303 if (Record->isUnion()) {
12304 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12305 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12306 if (RDecl->getDefinition()) {
12307 // C++ [class.union]p1: An object of a class with a non-trivial
12308 // constructor, a non-trivial copy constructor, a non-trivial
12309 // destructor, or a non-trivial copy assignment operator
12310 // cannot be a member of a union, nor can an array of such
12311 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000012312 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000012313 NewFD->setInvalidDecl();
12314 }
12315 }
12316
12317 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000012318 // the program is ill-formed, except when compiling with MSVC extensions
12319 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000012320 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000012321 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12322 diag::ext_union_member_of_reference_type :
12323 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000012324 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000012325 if (!getLangOpts().MicrosoftExt)
12326 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000012327 }
12328 }
12329 }
12330
Douglas Gregor1efa4372009-03-11 18:59:21 +000012331 // FIXME: We need to pass in the attributes given an AST
12332 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000012333 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000012334 // FIXME: The current scope is almost... but not entirely... correct here.
12335 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000012336
Richard Smith848e1f12013-02-01 08:12:08 +000012337 if (NewFD->hasAttrs())
12338 CheckAlignasUnderalignment(NewFD);
12339 }
12340
John McCall31168b02011-06-15 23:02:42 +000012341 // In auto-retain/release, infer strong retension for fields of
12342 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012343 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000012344 NewFD->setInvalidDecl();
12345
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000012346 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000012347 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000012348
Douglas Gregor4261e4c2009-03-11 20:50:30 +000012349 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000012350 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000012351}
12352
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012353bool Sema::CheckNontrivialField(FieldDecl *FD) {
12354 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012355 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012356
Nick Lewycky7a2a4792013-06-25 23:22:23 +000012357 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12358 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012359
12360 QualType EltTy = Context.getBaseElementType(FD->getType());
12361 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000012362 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012363 if (RDecl->getDefinition()) {
12364 // We check for copy constructors before constructors
12365 // because otherwise we'll never get complaints about
12366 // copy constructors.
12367
12368 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000012369 // We're required to check for any non-trivial constructors. Since the
12370 // implicit default constructor is suppressed if there are any
12371 // user-declared constructors, we just need to check that there is a
12372 // trivial default constructor and a trivial copy constructor. (We don't
12373 // worry about move constructors here, since this is a C++98 check.)
12374 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012375 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000012376 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000012377 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000012378 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012379 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000012380 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012381 member = CXXDestructor;
12382
12383 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012384 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012385 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000012386 // Objective-C++ ARC: it is an error to have a non-trivial field of
12387 // a union. However, system headers in Objective-C programs
12388 // occasionally have Objective-C lifetime objects within unions,
12389 // and rather than cause the program to fail, we make those
12390 // members unavailable.
12391 SourceLocation Loc = FD->getLocation();
12392 if (getSourceManager().isInSystemHeader(Loc)) {
12393 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000012394 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12395 "this system field has retaining ownership",
12396 Loc));
John McCall31168b02011-06-15 23:02:42 +000012397 return false;
12398 }
12399 }
Richard Smithf720df02011-10-19 20:41:51 +000012400
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012401 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000012402 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12403 diag::err_illegal_union_or_anon_struct_member)
12404 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000012405 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012406 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012407 }
12408 }
12409 }
Richard Smith92f241f2012-12-08 02:53:02 +000012410
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000012411 return false;
12412}
12413
Mike Stump11289f42009-09-09 15:08:12 +000012414/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000012415/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012416static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000012417TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000012418 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000012419 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000012420 case tok::objc_private: return ObjCIvarDecl::Private;
12421 case tok::objc_public: return ObjCIvarDecl::Public;
12422 case tok::objc_protected: return ObjCIvarDecl::Protected;
12423 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000012424 }
12425}
12426
Mike Stump11289f42009-09-09 15:08:12 +000012427/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000012428/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000012429Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000012430 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000012431 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000012432 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000012433
Fariborz Jahaniande615832008-04-10 23:32:45 +000012434 IdentifierInfo *II = D.getIdentifier();
12435 Expr *BitWidth = (Expr*)BitfieldWidth;
12436 SourceLocation Loc = DeclStart;
12437 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000012438
Fariborz Jahaniande615832008-04-10 23:32:45 +000012439 // FIXME: Unnamed fields can be handled in various different ways, for
12440 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000012441
John McCall8cb7bdf2010-06-04 23:28:52 +000012442 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12443 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000012444
Fariborz Jahaniande615832008-04-10 23:32:45 +000012445 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000012446 // 6.7.2.1p3, 6.7.2.1p4
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012447 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
Richard Smithf4c51d92012-02-04 09:53:13 +000012448 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012449 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000012450 } else {
12451 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000012452
Fariborz Jahaniande615832008-04-10 23:32:45 +000012453 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000012454
Fariborz Jahaniande615832008-04-10 23:32:45 +000012455 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000012456 if (T->isReferenceType()) {
12457 Diag(Loc, diag::err_ivar_reference_type);
12458 D.setInvalidType();
12459 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000012460 // C99 6.7.2.1p8: A member of a structure or union may have any type other
12461 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000012462 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000012463 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012464 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000012465 }
Mike Stump11289f42009-09-09 15:08:12 +000012466
Ted Kremenek73295fa2008-07-23 18:04:17 +000012467 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000012468 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000012469 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12470 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000012471 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012472 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000012473 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +000012474 return nullptr;
Daniel Dunbar229385c2010-04-02 18:29:09 +000012475 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000012476 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000012477 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000012478 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000012479 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000012480 EnclosingContext = IMPDecl->getClassInterface();
12481 assert(EnclosingContext && "Implementation has no class interface!");
12482 }
12483 else
12484 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012485 } else {
12486 if (ObjCCategoryDecl *CDecl =
12487 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000012488 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012489 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
Craig Topperc3ec1492014-05-26 06:22:03 +000012490 return nullptr;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012491 }
12492 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000012493 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012494 }
Mike Stump11289f42009-09-09 15:08:12 +000012495
Ted Kremenek73295fa2008-07-23 18:04:17 +000012496 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012497 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12498 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000012499 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000012500
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012501 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012502 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000012503 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012504 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012505 && !isa<TagDecl>(PrevDecl)) {
12506 Diag(Loc, diag::err_duplicate_member) << II;
12507 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12508 NewID->setInvalidDecl();
12509 }
12510 }
12511
Ted Kremenek73295fa2008-07-23 18:04:17 +000012512 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000012513 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000012514
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012515 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000012516 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000012517
John McCall31168b02011-06-15 23:02:42 +000012518 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012519 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000012520 NewID->setInvalidDecl();
12521
Douglas Gregor3baa6702011-09-12 16:11:24 +000012522 if (D.getDeclSpec().isModulePrivateSpecified())
12523 NewID->setModulePrivate();
12524
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012525 if (II) {
12526 // FIXME: When interfaces are DeclContexts, we'll need to add
12527 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000012528 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012529 IdResolver.AddDecl(NewID);
12530 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012531
John McCall5fb5df92012-06-20 06:18:46 +000012532 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012533 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000012534 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012535
John McCall48871652010-08-21 09:40:31 +000012536 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000012537}
12538
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012539/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000012540/// class and class extensions. For every class \@interface and class
12541/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012542/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012543void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012544 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000012545 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012546 return;
12547
12548 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12549 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12550
Richard Smithcaf33902011-10-10 18:28:20 +000012551 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012552 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012553 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012554 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012555 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012556 if (!CD->IsClassExtension())
12557 return;
12558 }
12559 // No need to add this to end of @implementation.
12560 else
12561 return;
12562 }
12563 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000012564 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12565 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012566
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012567 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Craig Topperc3ec1492014-05-26 06:22:03 +000012568 DeclLoc, DeclLoc, nullptr,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012569 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000012570 Context.getTrivialTypeSourceInfo(Context.CharTy,
12571 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012572 ObjCIvarDecl::Private, BW,
12573 true);
12574 AllIvarDecls.push_back(Ivar);
12575}
12576
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012577void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12578 ArrayRef<Decl *> Fields, SourceLocation LBrac,
12579 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000012580 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000012581
Eric Christopher7457aaf2012-07-19 22:22:51 +000012582 // If this is an Objective-C @implementation or category and we have
12583 // new fields here we should reset the layout of the interface since
12584 // it will now change.
12585 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12586 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12587 switch (DC->getKind()) {
12588 default: break;
12589 case Decl::ObjCCategory:
12590 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12591 break;
12592 case Decl::ObjCImplementation:
12593 Context.
12594 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12595 break;
12596 }
12597 }
12598
Eli Friedmana7679412012-02-07 05:00:47 +000012599 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12600
12601 // Start counting up the number of named members; make sure to include
12602 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000012603 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000012604 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000012605 for (const auto *I : Record->decls()) {
12606 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000012607 if (IFD->getDeclName())
12608 ++NumNamedMembers;
12609 }
12610 }
12611
12612 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012613 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000012614
John McCall31168b02011-06-15 23:02:42 +000012615 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012616 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000012617 i != end; ++i) {
12618 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000012619
Chris Lattner720a0542007-01-25 00:44:24 +000012620 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000012621 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000012622
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012623 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000012624 // Remember all fields written by the user.
12625 RecFields.push_back(FD);
12626 }
Mike Stump11289f42009-09-09 15:08:12 +000012627
Chris Lattner73bf7b42009-03-05 22:45:59 +000012628 // If the field is already invalid for some reason, don't emit more
12629 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000012630 if (FD->isInvalidDecl()) {
12631 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000012632 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000012633 }
Mike Stump11289f42009-09-09 15:08:12 +000012634
Douglas Gregorac1fb652009-03-24 19:52:54 +000012635 // C99 6.7.2.1p2:
12636 // A structure or union shall not contain a member with
12637 // incomplete or function type (hence, a structure shall not
12638 // contain an instance of itself, but may contain a pointer to
12639 // an instance of itself), except that the last member of a
12640 // structure with more than one named member may have incomplete
12641 // array type; such a structure (and any union containing,
12642 // possibly recursively, a member that is such a structure)
12643 // shall not be a member of a structure or an element of an
12644 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000012645 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012646 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000012647 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012648 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000012649 FD->setInvalidDecl();
12650 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012651 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000012652 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000012653 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000012654 ((getLangOpts().MicrosoftExt ||
12655 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000012656 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012657 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000012658 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000012659 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000012660 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000012661 unsigned DiagID = 0;
12662 if (Record->isUnion())
12663 DiagID = getLangOpts().MicrosoftExt
12664 ? diag::ext_flexible_array_union_ms
12665 : getLangOpts().CPlusPlus
12666 ? diag::ext_flexible_array_union_gnu
12667 : diag::err_flexible_array_union;
12668 else if (Fields.size() == 1)
12669 DiagID = getLangOpts().MicrosoftExt
12670 ? diag::ext_flexible_array_empty_aggregate_ms
12671 : getLangOpts().CPlusPlus
12672 ? diag::ext_flexible_array_empty_aggregate_gnu
12673 : NumNamedMembers < 1
12674 ? diag::err_flexible_array_empty_aggregate
12675 : 0;
12676
12677 if (DiagID)
12678 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12679 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000012680 // While the layout of types that contain virtual bases is not specified
12681 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12682 // virtual bases after the derived members. This would make a flexible
12683 // array member declared at the end of an object not adjacent to the end
12684 // of the type.
12685 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12686 if (RD->getNumVBases() != 0)
12687 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12688 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000012689 if (!getLangOpts().C99)
12690 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12691 << FD->getDeclName() << Record->getTagKind();
12692
Richard Smith6fa28ff2014-01-11 00:53:35 +000012693 // If the element type has a non-trivial destructor, we would not
12694 // implicitly destroy the elements, so disallow it for now.
12695 //
12696 // FIXME: GCC allows this. We should probably either implicitly delete
12697 // the destructor of the containing class, or just allow this.
12698 QualType BaseElem = Context.getBaseElementType(FD->getType());
12699 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12700 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000012701 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000012702 FD->setInvalidDecl();
12703 EnclosingDecl->setInvalidDecl();
12704 continue;
12705 }
Chris Lattner720a0542007-01-25 00:44:24 +000012706 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000012707 if (Record)
12708 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000012709 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000012710 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000012711 diag::err_field_incomplete)) {
12712 // Incomplete type
12713 FD->setInvalidDecl();
12714 EnclosingDecl->setInvalidDecl();
12715 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012716 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000012717 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12718 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012719 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012720 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012721 } else {
12722 // If this is a struct/class and this is not the last element, reject
12723 // it. Note that GCC supports variable sized arrays in the middle of
12724 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012725 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012726 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012727 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012728 else {
12729 // We support flexible arrays at the end of structs in
12730 // other structs as an extension.
12731 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12732 << FD->getDeclName();
12733 if (Record)
12734 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012735 }
Chris Lattner720a0542007-01-25 00:44:24 +000012736 }
12737 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012738 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12739 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12740 diag::err_abstract_type_in_decl,
12741 AbstractIvarType)) {
12742 // Ivars can not have abstract class types
12743 FD->setInvalidDecl();
12744 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012745 if (Record && FDTTy->getDecl()->hasObjectMember())
12746 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012747 if (Record && FDTTy->getDecl()->hasVolatileMember())
12748 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012749 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012750 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012751 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12752 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12753 QualType T = Context.getObjCObjectPointerType(FD->getType());
12754 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012755 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12756 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12757 // It's an error in ARC if a field has lifetime.
12758 // We don't want to report this in a system header, though,
12759 // so we just make the field unavailable.
12760 // FIXME: that's really not sufficient; we need to make the type
12761 // itself invalid to, say, initialize or copy.
12762 QualType T = FD->getType();
12763 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12764 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12765 SourceLocation loc = FD->getLocation();
12766 if (getSourceManager().isInSystemHeader(loc)) {
12767 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012768 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12769 "this system field has retaining ownership",
12770 loc));
John McCall31168b02011-06-15 23:02:42 +000012771 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012772 } else {
12773 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012774 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012775 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012776 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012777 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012778 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012779 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012780 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012781 if (FD->getType()->isObjCObjectPointerType() ||
12782 FD->getType().isObjCGCStrong())
12783 Record->setHasObjectMember(true);
12784 else if (Context.getAsArrayType(FD->getType())) {
12785 QualType BaseType = Context.getBaseElementType(FD->getType());
12786 if (BaseType->isRecordType() &&
12787 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012788 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012789 else if (BaseType->isObjCObjectPointerType() ||
12790 BaseType.isObjCGCStrong())
12791 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012792 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012793 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012794 if (Record && FD->getType().isVolatileQualified())
12795 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012796 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012797 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012798 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012799 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012800
Chris Lattner82625602007-01-24 02:26:21 +000012801 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012802 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012803 bool Completed = false;
12804 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12805 if (!CXXRecord->isInvalidDecl()) {
12806 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012807 for (CXXRecordDecl::conversion_iterator
12808 I = CXXRecord->conversion_begin(),
12809 E = CXXRecord->conversion_end(); I != E; ++I)
12810 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012811
12812 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012813 if (CXXRecord->hasUserDeclaredDestructor()) {
12814 // Adjust user-defined destructor exception spec.
12815 if (getLangOpts().CPlusPlus11)
12816 AdjustDestructorExceptionSpec(CXXRecord,
12817 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012818 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012819
Douglas Gregor8fb95122010-09-29 00:15:42 +000012820 // Add any implicitly-declared members to this class.
12821 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12822
12823 // If we have virtual base classes, we may end up finding multiple
12824 // final overriders for a given virtual function. Check for this
12825 // problem now.
12826 if (CXXRecord->getNumVBases()) {
12827 CXXFinalOverriderMap FinalOverriders;
12828 CXXRecord->getFinalOverriders(FinalOverriders);
12829
12830 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12831 MEnd = FinalOverriders.end();
12832 M != MEnd; ++M) {
12833 for (OverridingMethods::iterator SO = M->second.begin(),
12834 SOEnd = M->second.end();
12835 SO != SOEnd; ++SO) {
12836 assert(SO->second.size() > 0 &&
12837 "Virtual function without overridding functions?");
12838 if (SO->second.size() == 1)
12839 continue;
12840
12841 // C++ [class.virtual]p2:
12842 // In a derived class, if a virtual member function of a base
12843 // class subobject has more than one final overrider the
12844 // program is ill-formed.
12845 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012846 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012847 Diag(M->first->getLocation(),
12848 diag::note_overridden_virtual_function);
12849 for (OverridingMethods::overriding_iterator
12850 OM = SO->second.begin(),
12851 OMEnd = SO->second.end();
12852 OM != OMEnd; ++OM)
12853 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012854 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012855
12856 Record->setInvalidDecl();
12857 }
12858 }
12859 CXXRecord->completeDefinition(&FinalOverriders);
12860 Completed = true;
12861 }
12862 }
12863 }
12864 }
12865
12866 if (!Completed)
12867 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012868
David Majnemer2c4e00a2014-01-29 22:07:36 +000012869 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012870 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012871
David Majnemer98c9ee22014-02-07 00:43:07 +000012872 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012873 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012874 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012875 IA->getSemanticSpelling());
12876 }
12877
Serge Pavlov3cb80222013-11-14 02:13:03 +000012878 // Check if the structure/union declaration is a type that can have zero
12879 // size in C. For C this is a language extension, for C++ it may cause
12880 // compatibility problems.
12881 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012882 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012883 CheckForZeroSize = true;
12884 } else {
12885 // For C++ filter out types that cannot be referenced in C code.
12886 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12887 CheckForZeroSize =
12888 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12889 !CXXRecord->isDependentType() &&
12890 CXXRecord->isCLike();
12891 }
12892 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012893 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012894 bool IsEmpty = true;
12895 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012896 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012897 E = Record->field_end();
12898 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12899 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012900 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012901 if (I->getBitWidthValue(Context) > 0)
12902 ZeroSize = false;
12903 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012904 ++NonBitFields;
12905 QualType FieldType = I->getType();
12906 if (FieldType->isIncompleteType() ||
12907 !Context.getTypeSizeInChars(FieldType).isZero())
12908 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012909 }
12910 }
12911
Serge Pavlov3cb80222013-11-14 02:13:03 +000012912 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12913 // allowed in C++, but warn if its declaration is inside
12914 // extern "C" block.
12915 if (ZeroSize) {
12916 Diag(RecLoc, getLangOpts().CPlusPlus ?
12917 diag::warn_zero_size_struct_union_in_extern_c :
12918 diag::warn_zero_size_struct_union_compat)
12919 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12920 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012921
Serge Pavlov3cb80222013-11-14 02:13:03 +000012922 // Structs without named members are extension in C (C99 6.7.2.1p7),
12923 // but are accepted by GCC.
12924 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12925 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12926 diag::ext_no_named_members_in_struct_union)
12927 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012928 }
12929 }
Chris Lattner622c1932008-02-06 00:51:33 +000012930 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012931 ObjCIvarDecl **ClsFields =
12932 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012933 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012934 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012935 // Add ivar's to class's DeclContext.
12936 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12937 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012938 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012939 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012940 // Must enforce the rule that ivars in the base classes may not be
12941 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012942 if (ID->getSuperClass())
12943 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012944 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012945 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012946 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012947 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12948 // Ivar declared in @implementation never belongs to the implementation.
12949 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012950 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012951 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012952 IMPDecl->setIvarLBraceLoc(LBrac);
12953 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012954 } else if (ObjCCategoryDecl *CDecl =
12955 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012956 // case of ivars in class extension; all other cases have been
12957 // reported as errors elsewhere.
12958 // FIXME. Class extension does not have a LocEnd field.
12959 // CDecl->setLocEnd(RBrac);
12960 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012961 // Diagnose redeclaration of private ivars.
12962 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012963 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012964 if (IDecl) {
12965 if (const ObjCIvarDecl *ClsIvar =
12966 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12967 Diag(ClsFields[i]->getLocation(),
12968 diag::err_duplicate_ivar_declaration);
12969 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12970 continue;
12971 }
Aaron Ballmanb4a53452014-03-13 21:57:01 +000012972 for (const auto *Ext : IDecl->known_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012973 if (const ObjCIvarDecl *ClsExtIvar
12974 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012975 Diag(ClsFields[i]->getLocation(),
12976 diag::err_duplicate_ivar_declaration);
12977 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12978 continue;
12979 }
12980 }
12981 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012982 ClsFields[i]->setLexicalDeclContext(CDecl);
12983 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012984 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012985 CDecl->setIvarLBraceLoc(LBrac);
12986 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012987 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012988 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012989
12990 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012991 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012992}
12993
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012994/// \brief Determine whether the given integral value is representable within
12995/// the given type T.
12996static bool isRepresentableIntegerValue(ASTContext &Context,
12997 llvm::APSInt &Value,
12998 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012999 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000013000 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013001
Douglas Gregor0bf31402010-10-08 23:50:27 +000013002 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013003 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000013004 --BitWidth;
13005 return Value.getActiveBits() <= BitWidth;
13006 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013007 return Value.getMinSignedBits() <= BitWidth;
13008}
13009
13010// \brief Given an integral type, return the next larger integral type
13011// (or a NULL type of no such type exists).
13012static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13013 // FIXME: Int128/UInt128 support, which also needs to be introduced into
13014 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000013015 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013016 const unsigned NumTypes = 4;
13017 QualType SignedIntegralTypes[NumTypes] = {
13018 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13019 };
13020 QualType UnsignedIntegralTypes[NumTypes] = {
13021 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13022 Context.UnsignedLongLongTy
13023 };
13024
13025 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013026 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13027 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013028 for (unsigned I = 0; I != NumTypes; ++I)
13029 if (Context.getTypeSize(Types[I]) > BitWidth)
13030 return Types[I];
13031
13032 return QualType();
13033}
13034
Douglas Gregor954f6b272009-03-17 19:05:46 +000013035EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13036 EnumConstantDecl *LastEnumConst,
13037 SourceLocation IdLoc,
13038 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000013039 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013040 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013041 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000013042 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000013043
13044 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
Craig Topperc3ec1492014-05-26 06:22:03 +000013045 Val = nullptr;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000013046
Eli Friedman7c6515a2011-12-06 00:10:34 +000013047 if (Val)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013048 Val = DefaultLvalueConversion(Val).get();
Eli Friedman7c6515a2011-12-06 00:10:34 +000013049
Douglas Gregorb2186fe2009-11-06 00:03:12 +000013050 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000013051 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000013052 EltTy = Context.DependentTy;
13053 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000013054 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013055 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000013056 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000013057 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13058 // constant-expression in the enumerator-definition shall be a converted
13059 // constant expression of the underlying type.
13060 EltTy = Enum->getIntegerType();
13061 ExprResult Converted =
13062 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13063 CCEK_Enumerator);
13064 if (Converted.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +000013065 Val = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +000013066 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013067 Val = Converted.get();
Richard Smithf8379a02012-01-18 23:55:52 +000013068 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000013069 !(Val = VerifyIntegerConstantExpression(Val,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013070 &EnumVal).get())) {
Richard Smithf8379a02012-01-18 23:55:52 +000013071 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000013072 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000013073 if (Enum->isFixed()) {
13074 EltTy = Enum->getIntegerType();
13075
Richard Smithf8379a02012-01-18 23:55:52 +000013076 // In Obj-C and Microsoft mode, require the enumeration value to be
13077 // representable in the underlying type of the enumeration. In C++11,
13078 // we perform a non-narrowing conversion as part of converted constant
13079 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000013080 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000013081 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000013082 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013083 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +000013084 } else
13085 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000013086 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013087 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
David Blaikiebbafb8a2012-03-11 07:00:24 +000013088 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000013089 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000013090 // If the underlying type is not fixed, the type of each enumerator
13091 // is the type of its initializing value:
13092 // - If an initializer is specified for an enumerator, the
13093 // initializing value has the same type as the expression.
13094 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000013095 } else {
13096 // C99 6.7.2.2p2:
13097 // The expression that defines the value of an enumeration constant
13098 // shall be an integer constant expression that has a value
13099 // representable as an int.
13100
13101 // Complain if the value is not representable in an int.
13102 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13103 Diag(IdLoc, diag::ext_enum_value_not_int)
13104 << EnumVal.toString(10) << Val->getSourceRange()
13105 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13106 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13107 // Force the type of the expression to 'int'.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013108 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
Eli Friedman2beed112012-02-07 04:34:38 +000013109 }
13110 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000013111 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000013112 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000013113 }
13114 }
Mike Stump11289f42009-09-09 15:08:12 +000013115
Douglas Gregor954f6b272009-03-17 19:05:46 +000013116 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000013117 if (Enum->isDependentType())
13118 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013119 else if (!LastEnumConst) {
13120 // C++0x [dcl.enum]p5:
13121 // If the underlying type is not fixed, the type of each enumerator
13122 // is the type of its initializing value:
13123 // - If no initializer is specified for the first enumerator, the
13124 // initializing value has an unspecified integral type.
13125 //
13126 // GCC uses 'int' for its unspecified integral type, as does
13127 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000013128 if (Enum->isFixed()) {
13129 EltTy = Enum->getIntegerType();
13130 }
13131 else {
13132 EltTy = Context.IntTy;
13133 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013134 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000013135 // Assign the last value + 1.
13136 EnumVal = LastEnumConst->getInitVal();
13137 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013138 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000013139
13140 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013141 if (EnumVal < LastEnumConst->getInitVal()) {
13142 // C++0x [dcl.enum]p5:
13143 // If the underlying type is not fixed, the type of each enumerator
13144 // is the type of its initializing value:
13145 //
13146 // - Otherwise the type of the initializing value is the same as
13147 // the type of the initializing value of the preceding enumerator
13148 // unless the incremented value is not representable in that type,
13149 // in which case the type is an unspecified integral type
13150 // sufficient to contain the incremented value. If no such type
13151 // exists, the program is ill-formed.
13152 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000013153 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013154 // There is no integral type larger enough to represent this
13155 // value. Complain, then allow the value to wrap around.
13156 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000013157 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000013158 ++EnumVal;
13159 if (Enum->isFixed())
13160 // When the underlying type is fixed, this is ill-formed.
13161 Diag(IdLoc, diag::err_enumerator_wrapped)
13162 << EnumVal.toString(10)
13163 << EltTy;
13164 else
Richard Smithfaf156a2014-03-05 22:54:58 +000013165 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000013166 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013167 } else {
13168 EltTy = T;
13169 }
13170
13171 // Retrieve the last enumerator's value, extent that type to the
13172 // type that is supposed to be large enough to represent the incremented
13173 // value, then increment.
13174 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013175 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000013176 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013177 ++EnumVal;
13178
13179 // If we're not in C++, diagnose the overflow of enumerator values,
13180 // which in C99 means that the enumerator value is not representable in
13181 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13182 // permits enumerator values that are representable in some larger
13183 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013184 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013185 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000013186 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013187 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13188 // Enforce C99 6.7.2.2p2 even when we compute the next value.
13189 Diag(IdLoc, diag::ext_enum_value_not_int)
13190 << EnumVal.toString(10) << 1;
13191 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000013192 }
13193 }
Mike Stump11289f42009-09-09 15:08:12 +000013194
Douglas Gregordc70c3a2010-03-02 17:53:14 +000013195 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013196 // Make the enumerator value match the signedness and size of the
13197 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000013198 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013199 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013200 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000013201
Douglas Gregor954f6b272009-03-17 19:05:46 +000013202 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000013203 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000013204}
13205
13206
John McCall811a0f52010-10-22 23:36:17 +000013207Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13208 SourceLocation IdLoc, IdentifierInfo *Id,
13209 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000013210 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000013211 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000013212 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000013213 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000013214
Chris Lattner1a76a3c2007-08-26 06:24:45 +000013215 // The scope passed in may not be a decl scope. Zip up the scope tree until
13216 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000013217 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000013218
Chris Lattner8116d1b2007-01-25 22:38:29 +000013219 // Verify that there isn't already something declared with this name in this
13220 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013221 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000013222 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000013223 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000013224 // Maybe we will complain about the shadowed template parameter.
13225 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13226 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013227 PrevDecl = nullptr;
Douglas Gregor5101c242008-12-05 18:15:24 +000013228 }
13229
13230 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000013231 // When in C++, we may get a TagDecl with the same name; in this case the
13232 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013233 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000013234 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000013235 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000013236 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000013237 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000013238 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000013239 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000013240 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000013241 return nullptr;
Chris Lattner8116d1b2007-01-25 22:38:29 +000013242 }
13243 }
Chris Lattner4ef40012007-06-11 01:28:17 +000013244
Aaron Ballman24a10472012-07-19 03:12:23 +000013245 // C++ [class.mem]p15:
13246 // If T is the name of a class, then each of the following shall have a name
13247 // different from T:
13248 // - every enumerator of every member of class T that is an unscoped
13249 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000013250 if (CXXRecordDecl *Record
13251 = dyn_cast<CXXRecordDecl>(
13252 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000013253 if (!TheEnumDecl->isScoped() &&
13254 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000013255 Diag(IdLoc, diag::err_member_name_of_class) << Id;
13256
John McCall811a0f52010-10-22 23:36:17 +000013257 EnumConstantDecl *New =
13258 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000013259
John McCall553c0792010-01-23 00:46:32 +000013260 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000013261 // Process attributes.
13262 if (Attr) ProcessDeclAttributeList(S, New, Attr);
13263
13264 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000013265 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000013266 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000013267 }
Douglas Gregor2f521192008-12-17 02:04:30 +000013268
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000013269 ActOnDocumentableDecl(New);
13270
John McCall48871652010-08-21 09:40:31 +000013271 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000013272}
13273
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000013274// Returns true when the enum initial expression does not trigger the
13275// duplicate enum warning. A few common cases are exempted as follows:
13276// Element2 = Element1
13277// Element2 = Element1 + 1
13278// Element2 = Element1 - 1
13279// Where Element2 and Element1 are from the same enum.
13280static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13281 Expr *InitExpr = ECD->getInitExpr();
13282 if (!InitExpr)
13283 return true;
13284 InitExpr = InitExpr->IgnoreImpCasts();
13285
13286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13287 if (!BO->isAdditiveOp())
13288 return true;
13289 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13290 if (!IL)
13291 return true;
13292 if (IL->getValue() != 1)
13293 return true;
13294
13295 InitExpr = BO->getLHS();
13296 }
13297
13298 // This checks if the elements are from the same enum.
13299 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13300 if (!DRE)
13301 return true;
13302
13303 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13304 if (!EnumConstant)
13305 return true;
13306
13307 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13308 Enum)
13309 return true;
13310
13311 return false;
13312}
13313
13314struct DupKey {
13315 int64_t val;
13316 bool isTombstoneOrEmptyKey;
13317 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13318 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13319};
13320
13321static DupKey GetDupKey(const llvm::APSInt& Val) {
13322 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13323 false);
13324}
13325
13326struct DenseMapInfoDupKey {
13327 static DupKey getEmptyKey() { return DupKey(0, true); }
13328 static DupKey getTombstoneKey() { return DupKey(1, true); }
13329 static unsigned getHashValue(const DupKey Key) {
13330 return (unsigned)(Key.val * 37);
13331 }
13332 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13333 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13334 LHS.val == RHS.val;
13335 }
13336};
13337
13338// Emits a warning when an element is implicitly set a value that
13339// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013340static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13341 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000013342 QualType EnumType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013343 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000013344 return;
13345 // Avoid anonymous enums
13346 if (!Enum->getIdentifier())
13347 return;
13348
13349 // Only check for small enums.
13350 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13351 return;
13352
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013353 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13354 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000013355
13356 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13357 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13358 ValueToVectorMap;
13359
13360 DuplicatesVector DupVector;
13361 ValueToVectorMap EnumMap;
13362
13363 // Populate the EnumMap with all values represented by enum constants without
13364 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013365 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000013366 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000013367
13368 // Null EnumConstantDecl means a previous diagnostic has been emitted for
13369 // this constant. Skip this enum since it may be ill-formed.
13370 if (!ECD) {
13371 return;
13372 }
13373
13374 if (ECD->getInitExpr())
13375 continue;
13376
13377 DupKey Key = GetDupKey(ECD->getInitVal());
13378 DeclOrVector &Entry = EnumMap[Key];
13379
13380 // First time encountering this value.
13381 if (Entry.isNull())
13382 Entry = ECD;
13383 }
13384
13385 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013386 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000013387 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13388 if (!ValidDuplicateEnum(ECD, Enum))
13389 continue;
13390
13391 DupKey Key = GetDupKey(ECD->getInitVal());
13392
13393 DeclOrVector& Entry = EnumMap[Key];
13394 if (Entry.isNull())
13395 continue;
13396
13397 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13398 // Ensure constants are different.
13399 if (D == ECD)
13400 continue;
13401
13402 // Create new vector and push values onto it.
13403 ECDVector *Vec = new ECDVector();
13404 Vec->push_back(D);
13405 Vec->push_back(ECD);
13406
13407 // Update entry to point to the duplicates vector.
13408 Entry = Vec;
13409
13410 // Store the vector somewhere we can consult later for quick emission of
13411 // diagnostics.
13412 DupVector.push_back(Vec);
13413 continue;
13414 }
13415
13416 ECDVector *Vec = Entry.get<ECDVector*>();
13417 // Make sure constants are not added more than once.
13418 if (*Vec->begin() == ECD)
13419 continue;
13420
13421 Vec->push_back(ECD);
13422 }
13423
13424 // Emit diagnostics.
13425 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13426 DupVectorEnd = DupVector.end();
13427 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13428 ECDVector *Vec = *DupVectorIter;
13429 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13430
13431 // Emit warning for one enum constant.
13432 ECDVector::iterator I = Vec->begin();
13433 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13434 << (*I)->getName() << (*I)->getInitVal().toString(10)
13435 << (*I)->getSourceRange();
13436 ++I;
13437
13438 // Emit one note for each of the remaining enum constants with
13439 // the same value.
13440 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13441 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13442 << (*I)->getName() << (*I)->getInitVal().toString(10)
13443 << (*I)->getSourceRange();
13444 delete Vec;
13445 }
13446}
13447
Mike Stump6814d1c2009-05-16 07:06:02 +000013448void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000013449 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013450 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013451 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000013452 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000013453 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013454
13455 if (Attr)
13456 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000013457
Eli Friedmand0e60972009-12-11 01:34:50 +000013458 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013459 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000013460 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000013461 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000013462 if (!ECD) continue;
13463
13464 ECD->setType(EnumType);
13465 }
13466
John McCall9aa35be2010-05-06 08:49:23 +000013467 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000013468 return;
13469 }
13470
Chris Lattner67933c02007-08-28 05:10:31 +000013471 // TODO: If the result value doesn't fit in an int, it must be a long or long
13472 // long value. ISO C does not support this, but GCC does as an extension,
13473 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000013474 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13475 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13476 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013477
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013478 // Verify that all the values are okay, compute the size of the values, and
13479 // reverse the list.
13480 unsigned NumNegativeBits = 0;
13481 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000013482
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013483 // Keep track of whether all elements have type int.
13484 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000013485
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013486 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000013487 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000013488 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013489 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000013490
Chris Lattnerbf478cb2007-08-28 05:27:00 +000013491 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000013492
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013493 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000013494 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000013495 NumPositiveBits = std::max(NumPositiveBits,
13496 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013497 else
Chris Lattner49f980c2008-01-14 21:47:29 +000013498 NumNegativeBits = std::max(NumNegativeBits,
13499 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000013500
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013501 // Keep track of whether every enum element has type int (very commmon).
13502 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000013503 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000013504 }
Mike Stump11289f42009-09-09 15:08:12 +000013505
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013506 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013507 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013508 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013509
John McCall56774992009-12-09 09:09:27 +000013510 // C++0x N3000 [conv.prom]p3:
13511 // An rvalue of an unscoped enumeration type whose underlying
13512 // type is not fixed can be converted to an rvalue of the first
13513 // of the following types that can represent all the values of
13514 // the enumeration: int, unsigned int, long int, unsigned long
13515 // int, long long int, or unsigned long long int.
13516 // C99 6.4.4.3p2:
13517 // An identifier declared as an enumeration constant has type int.
13518 // The C99 rule is modified by a gcc extension
13519 QualType BestPromotionType;
13520
Aaron Ballman9ead1242013-12-19 02:39:40 +000013521 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000013522 // -fshort-enums is the equivalent to specifying the packed attribute on all
13523 // enum definitions.
13524 if (LangOpts.ShortEnums)
13525 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013526
Douglas Gregor0bf31402010-10-08 23:50:27 +000013527 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000013528 BestType = Enum->getIntegerType();
13529 if (BestType->isPromotableIntegerType())
13530 BestPromotionType = Context.getPromotedIntegerType(BestType);
13531 else
13532 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000013533 // We don't need to set BestWidth, because BestType is going to be the type
13534 // of the enumerators, but we do anyway because otherwise some compilers
13535 // warn that it might be used uninitialized.
13536 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000013537 }
13538 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000013539 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013540 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013541 // If it's packed, check also if it fits a char or a short.
13542 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013543 BestType = Context.SignedCharTy;
13544 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000013545 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013546 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013547 BestType = Context.ShortTy;
13548 BestWidth = ShortWidth;
13549 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013550 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013551 BestWidth = IntWidth;
13552 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013553 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013554
John McCall56774992009-12-09 09:09:27 +000013555 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013556 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000013557 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013558 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013559
Chris Lattner3a370bf2007-08-29 17:31:48 +000013560 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000013561 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013562 BestType = Context.LongLongTy;
13563 }
13564 }
John McCall56774992009-12-09 09:09:27 +000013565 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013566 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000013567 // If there is no negative value, figure out the smallest type that fits
13568 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013569 // If it's packed, check also if it fits a char or a short.
13570 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013571 BestType = Context.UnsignedCharTy;
13572 BestPromotionType = Context.IntTy;
13573 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013574 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013575 BestType = Context.UnsignedShortTy;
13576 BestPromotionType = Context.IntTy;
13577 BestWidth = ShortWidth;
13578 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013579 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013580 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000013581 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013582 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013583 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013584 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000013585 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013586 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013587 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013588 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013589 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000013590 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013591 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013592 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013593 "How could an initializer get larger than ULL?");
13594 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013595 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013596 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013597 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013598 }
13599 }
Mike Stump11289f42009-09-09 15:08:12 +000013600
Chris Lattner3a370bf2007-08-29 17:31:48 +000013601 // Loop over all of the enumerator constants, changing their types to match
13602 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013603 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000013604 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013605 if (!ECD) continue; // Already issued a diagnostic.
13606
13607 // Standard C says the enumerators have int type, but we allow, as an
13608 // extension, the enumerators to be larger than int size. If each
13609 // enumerator value fits in an int, type it as an int, otherwise type it the
13610 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
13611 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000013612
13613 // Determine whether the value fits into an int.
13614 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013615
13616 // If it fits into an integer type, force it. Otherwise force it to match
13617 // the enum decl type.
13618 QualType NewTy;
13619 unsigned NewWidth;
13620 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000013621 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000013622 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013623 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000013624 NewTy = Context.IntTy;
13625 NewWidth = IntWidth;
13626 NewSign = true;
13627 } else if (ECD->getType() == BestType) {
13628 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000013629 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013630 // C++ [dcl.enum]p4: Following the closing brace of an
13631 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013632 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013633 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013634 continue;
13635 } else {
13636 NewTy = BestType;
13637 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013638 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013639 }
13640
13641 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000013642 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013643 InitVal.setIsSigned(NewSign);
13644 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000013645
Chris Lattner3a370bf2007-08-29 17:31:48 +000013646 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000013647 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000013648 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000013649 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000013650 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000013651 ECD->getInitExpr(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013652 /*base paths*/ nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013653 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000013654 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013655 // C++ [dcl.enum]p4: Following the closing brace of an
13656 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013657 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013658 ECD->setType(EnumType);
13659 else
13660 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013661 }
Mike Stump11289f42009-09-09 15:08:12 +000013662
John McCall9aa35be2010-05-06 08:49:23 +000013663 Enum->completeDefinition(BestType, BestPromotionType,
13664 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000013665
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013666 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000013667
13668 // Now that the enum type is defined, ensure it's not been underaligned.
13669 if (Enum->hasAttrs())
13670 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013671}
Chris Lattner1300fb92007-01-23 23:42:53 +000013672
Abramo Bagnara348823a2011-03-03 14:20:18 +000013673Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13674 SourceLocation StartLoc,
13675 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000013676 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000013677
Douglas Gregor278f52e2009-05-30 00:08:05 +000013678 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000013679 AsmString, StartLoc,
13680 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013681 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000013682 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000013683}
Eli Friedman5ed51982009-06-05 02:44:36 +000013684
Richard Smith77944862014-03-02 05:58:18 +000013685static void checkModuleImportContext(Sema &S, Module *M,
13686 SourceLocation ImportLoc,
13687 DeclContext *DC) {
13688 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13689 switch (LSD->getLanguage()) {
13690 case LinkageSpecDecl::lang_c:
13691 if (!M->IsExternC) {
13692 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13693 << M->getFullModuleName();
13694 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13695 return;
13696 }
13697 break;
13698 case LinkageSpecDecl::lang_cxx:
13699 break;
13700 }
13701 DC = LSD->getParent();
13702 }
13703
13704 while (isa<LinkageSpecDecl>(DC))
13705 DC = DC->getParent();
13706 if (!isa<TranslationUnitDecl>(DC)) {
13707 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13708 << M->getFullModuleName() << DC;
13709 S.Diag(cast<Decl>(DC)->getLocStart(),
13710 diag::note_module_import_not_at_top_level)
13711 << DC;
13712 }
13713}
13714
Douglas Gregor22d09742012-01-03 18:04:46 +000013715DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13716 SourceLocation ImportLoc,
13717 ModuleIdPath Path) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000013718 Module *Mod =
13719 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13720 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013721 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013722 return true;
Richard Smith77944862014-03-02 05:58:18 +000013723
13724 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13725
Ben Langmuir527040e2014-05-05 05:31:33 +000013726 // FIXME: we should support importing a submodule within a different submodule
13727 // of the same top-level module. Until we do, make it an error rather than
13728 // silently ignoring the import.
13729 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13730 Diag(ImportLoc, diag::err_module_self_import)
13731 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
Ben Langmuirb537a3a2014-07-23 15:30:23 +000013732 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13733 Diag(ImportLoc, diag::err_module_import_in_implementation)
13734 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
Ben Langmuir527040e2014-05-05 05:31:33 +000013735
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013736 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013737 Module *ModCheck = Mod;
13738 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13739 // If we've run out of module parents, just drop the remaining identifiers.
13740 // We need the length to be consistent.
13741 if (!ModCheck)
13742 break;
13743 ModCheck = ModCheck->Parent;
13744
13745 IdentifierLocs.push_back(Path[I].second);
13746 }
13747
13748 ImportDecl *Import = ImportDecl::Create(Context,
13749 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013750 AtLoc.isValid()? AtLoc : ImportLoc,
13751 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013752 Context.getTranslationUnitDecl()->addDecl(Import);
13753 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013754}
13755
Richard Smithce587f52013-11-15 04:24:58 +000013756void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013757 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13758
Richard Smithce587f52013-11-15 04:24:58 +000013759 // FIXME: Should we synthesize an ImportDecl here?
Alp Tokerb6cc5922014-05-03 03:45:55 +000013760 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13761 /*Complain=*/true);
Richard Smithce587f52013-11-15 04:24:58 +000013762}
13763
Richard Smith3d23c422014-05-07 02:25:43 +000013764void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13765 Module *Mod) {
13766 // Bail if we're not allowed to implicitly import a module here.
13767 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13768 return;
13769
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013770 // Create the implicit import declaration.
13771 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13772 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13773 Loc, Mod, Loc);
13774 TU->addDecl(ImportD);
13775 Consumer.HandleImplicitImportDecl(ImportD);
13776
13777 // Make the module visible.
Alp Tokerb6cc5922014-05-03 03:45:55 +000013778 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13779 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013780}
13781
David Chisnall0867d9c2012-02-18 16:12:34 +000013782void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13783 IdentifierInfo* AliasName,
13784 SourceLocation PragmaLoc,
13785 SourceLocation NameLoc,
13786 SourceLocation AliasNameLoc) {
13787 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13788 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013789 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13790 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013791
13792 if (PrevDecl)
13793 PrevDecl->addAttr(Attr);
13794 else
13795 (void)ExtnameUndeclaredIdentifiers.insert(
13796 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13797}
13798
Eli Friedman5ed51982009-06-05 02:44:36 +000013799void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13800 SourceLocation PragmaLoc,
13801 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013802 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013803
Eli Friedman5ed51982009-06-05 02:44:36 +000013804 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013805 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013806 } else {
13807 (void)WeakUndeclaredIdentifiers.insert(
13808 std::pair<IdentifierInfo*,WeakInfo>
Craig Topperc3ec1492014-05-26 06:22:03 +000013809 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013810 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013811}
13812
13813void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13814 IdentifierInfo* AliasName,
13815 SourceLocation PragmaLoc,
13816 SourceLocation NameLoc,
13817 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013818 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13819 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013820 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013821
Eli Friedman5ed51982009-06-05 02:44:36 +000013822 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013823 if (!PrevDecl->hasAttr<AliasAttr>())
13824 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013825 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013826 } else {
13827 (void)WeakUndeclaredIdentifiers.insert(
13828 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013829 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013830}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013831
13832Decl *Sema::getObjCDeclContext() const {
13833 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13834}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013835
13836AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013837 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013838 // If we are within an Objective-C method, we should consult
13839 // both the availability of the method as well as the
13840 // enclosing class. If the class is (say) deprecated,
13841 // the entire method is considered deprecated from the
13842 // purpose of checking if the current context is deprecated.
13843 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13844 AvailabilityResult R = MD->getAvailability();
13845 if (R != AR_Available)
13846 return R;
13847 D = MD->getClassInterface();
13848 }
13849 // If we are within an Objective-c @implementation, it
13850 // gets the same availability context as the @interface.
13851 else if (const ObjCImplementationDecl *ID =
13852 dyn_cast<ObjCImplementationDecl>(D)) {
13853 D = ID->getClassInterface();
13854 }
Fariborz Jahanian38c53fb2014-08-21 17:06:57 +000013855 // Recover from user error.
13856 return D ? D->getAvailability() : AR_Available;
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013857}