blob: e9c3c39b132389145d6c9ef080f698c5c09ffd53 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000015#include "TypeLocBuilder.h"
Chris Lattner622c1932008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000017#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000021#include "clang/AST/CommentDiagnostic.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000026#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000027#include "clang/AST/StmtCXX.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34#include "clang/Parse/ParseDiagnostic.h"
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000043#include "clang/Sema/Template.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000044#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000045#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000046#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000047#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000048#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000049using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000050using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000051
Richard Smithcd1c0552011-07-01 19:46:12 +000052Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53 if (OwnedType) {
54 Decl *Group[2] = { OwnedType, Ptr };
55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56 }
57
John McCall48871652010-08-21 09:40:31 +000058 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000059}
60
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000061namespace {
62
63class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64 public:
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
66 bool AllowTemplates=false)
67 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
68 AllowClassTemplates(AllowTemplates) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000069 WantExpressionKeywords = false;
70 WantCXXNamedCasts = false;
71 WantRemainingKeywords = false;
72 }
73
Craig Toppere14c0f82014-03-12 04:55:44 +000074 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000075 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
76 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
77 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
78 return (IsType || AllowedTemplate) &&
79 (AllowInvalidDecl || !ND->isInvalidDecl());
80 }
81 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000082 }
83
84 private:
85 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000086 bool WantClassName;
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000087 bool AllowClassTemplates;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000088};
89
90}
91
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +000092/// \brief Determine whether the token kind starts a simple-type-specifier.
93bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
94 switch (Kind) {
95 // FIXME: Take into account the current language when deciding whether a
96 // token kind is a valid type specifier
97 case tok::kw_short:
98 case tok::kw_long:
99 case tok::kw___int64:
100 case tok::kw___int128:
101 case tok::kw_signed:
102 case tok::kw_unsigned:
103 case tok::kw_void:
104 case tok::kw_char:
105 case tok::kw_int:
106 case tok::kw_half:
107 case tok::kw_float:
108 case tok::kw_double:
109 case tok::kw_wchar_t:
110 case tok::kw_bool:
111 case tok::kw___underlying_type:
112 return true;
113
114 case tok::annot_typename:
115 case tok::kw_char16_t:
116 case tok::kw_char32_t:
117 case tok::kw_typeof:
David Majnemera5e92552013-09-22 01:24:26 +0000118 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +0000119 case tok::kw_decltype:
120 return getLangOpts().CPlusPlus;
121
122 default:
123 break;
124 }
125
126 return false;
127}
128
Douglas Gregorec6e1892009-02-04 19:16:12 +0000129/// \brief If the identifier refers to a type name within this scope,
130/// return the declaration of that type.
131///
132/// This routine performs ordinary name lookup of the identifier II
133/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000134/// determine whether the name refers to a type. If so, returns an
135/// opaque pointer (actually a QualType) corresponding to that
136/// type. Otherwise, returns NULL.
Dmitri Gribenko5267fdf2013-05-03 13:12:11 +0000137ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000138 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000139 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000140 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000141 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000142 bool WantNontrivialTypeSourceInfo,
143 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000144 // Determine where we will perform name lookup.
145 DeclContext *LookupCtx = 0;
146 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000147 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000148 if (ObjectType->isRecordType())
149 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000150 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000151 LookupCtx = computeDeclContext(*SS, false);
152
153 if (!LookupCtx) {
154 if (isDependentScopeSpecifier(*SS)) {
155 // C++ [temp.res]p3:
156 // A qualified-id that refers to a type and in which the
157 // nested-name-specifier depends on a template-parameter (14.6.2)
158 // shall be prefixed by the keyword typename to indicate that the
159 // qualified-id denotes a type, forming an
160 // elaborated-type-specifier (7.1.5.3).
161 //
162 // We therefore do not perform any name lookup if the result would
163 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000164 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000165 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000166
John McCallc392f372010-06-11 00:33:02 +0000167 // We know from the grammar that this name refers to a type,
168 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000169 if (WantNontrivialTypeSourceInfo)
170 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
171
172 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000173 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000174 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000175 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000176
177 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000178 }
179
John McCallba7bf592010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000181 }
182
John McCall0b66eb32010-05-01 00:40:08 +0000183 if (!LookupCtx->isDependentContext() &&
184 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000185 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000186 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000187
188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189 // lookup for class-names.
190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191 LookupOrdinaryName;
192 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000193 if (LookupCtx) {
194 // Perform "qualified" name lookup into the declaration context we
195 // computed, which is either the type of the base of a member access
196 // expression or the declaration context associated with a prior
197 // nested-name-specifier.
198 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000199
Douglas Gregora25d65d2009-11-20 22:03:38 +0000200 if (ObjectTypePtr && Result.empty()) {
201 // C++ [basic.lookup.classref]p3:
202 // If the unqualified-id is ~type-name, the type-name is looked up
203 // in the context of the entire postfix-expression. If the type T of
204 // the object expression is of a class type C, the type-name is also
205 // looked up in the scope of class C. At least one of the lookups shall
206 // find a name that refers to (possibly cv-qualified) T.
207 LookupName(Result, S);
208 }
209 } else {
210 // Perform unqualified name lookup.
211 LookupName(Result, S);
212 }
213
Chris Lattnera3778332009-02-16 22:07:16 +0000214 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000215 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000216 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000217 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000218 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000219 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +0000221 Kind, S, SS, Validator,
222 CTK_ErrorRecovery);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000223 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
224 TemplateTy Template;
225 bool MemberOfUnknownSpecialization;
226 UnqualifiedId TemplateName;
227 TemplateName.setIdentifier(NewII, NameLoc);
228 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
229 CXXScopeSpec NewSS, *NewSSPtr = SS;
230 if (SS && NNS) {
231 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 NewSSPtr = &NewSS;
233 }
234 if (Correction && (NNS || NewII != &II) &&
235 // Ignore a correction to a template type as the to-be-corrected
236 // identifier is not a template (typo correction for template names
237 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000238 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000239 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
240 false, Template, MemberOfUnknownSpecialization))) {
241 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
242 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000243 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000244 WantNontrivialTypeSourceInfo);
245 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000246 diagnoseTypo(Correction,
247 PDiag(diag::err_unknown_type_or_class_name_suggest)
248 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000249 if (SS && NNS)
250 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
251 *CorrectedII = NewII;
252 return Ty;
253 }
254 }
255 }
256 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000257 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000258 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000259 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000261
Chris Lattnere40853a2009-10-25 22:09:09 +0000262 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000263 // Recover from type-hiding ambiguities by hiding the type. We'll
264 // do the lookup again when looking for an object, and we can
265 // diagnose the error then. If we don't do this, then the error
266 // about hiding the type will be immediately followed by an error
267 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000268 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
269 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000270 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000271 }
John McCall6538c932009-10-10 05:48:19 +0000272
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000273 // Look to see if we have a type anywhere in the list of results.
274 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
275 Res != ResEnd; ++Res) {
276 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000277 if (!IIDecl ||
278 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000279 IIDecl->getLocation().getRawEncoding())
280 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000281 }
282 }
283
284 if (!IIDecl) {
285 // None of the entities we found is a type, so there is no way
286 // to even assume that the result is a type. In this case, don't
287 // complain about the ambiguity. The parser will either try to
288 // perform this lookup again (e.g., as an object name), which
289 // will produce the ambiguity, or will complain that it expected
290 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000291 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000292 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000293 }
294
295 // We found a type within the ambiguous lookup; diagnose the
296 // ambiguity and then return that type. This might be the right
297 // answer, or it might not be, but it suppresses any attempt to
298 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000299 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000300
Chris Lattnera3778332009-02-16 22:07:16 +0000301 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000302 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000303 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000304 }
305
Chris Lattner17e15f12009-10-25 17:16:46 +0000306 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000307
Chris Lattner17e15f12009-10-25 17:16:46 +0000308 QualType T;
309 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000310 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000311
Chris Lattner17e15f12009-10-25 17:16:46 +0000312 if (T.isNull())
313 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-01-27 08:46:19 +0000314
315 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
316 // constructor or destructor name (in such a case, the scope specifier
317 // will be attached to the enclosing Expr or Decl node).
318 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor844cb502011-03-01 18:12:44 +0000319 if (WantNontrivialTypeSourceInfo) {
320 // Construct a type with type-source information.
321 TypeLocBuilder Builder;
322 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
323
324 T = getElaboratedType(ETK_None, *SS, T);
325 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000326 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-03-01 18:12:44 +0000327 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
328 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
329 } else {
330 T = getElaboratedType(ETK_None, *SS, T);
331 }
332 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000333 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000334 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000335 if (!HasTrailingDot)
336 T = Context.getObjCInterfaceType(IDecl);
337 }
338
339 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000340 // If it's not plausibly a type, suppress diagnostics.
341 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000342 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000343 }
John McCallba7bf592010-08-24 05:47:05 +0000344 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000345}
346
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000347/// isTagName() - This method is called *for error recovery purposes only*
348/// to determine if the specified name is a valid tag name ("struct foo"). If
349/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matosdc86f942012-08-31 18:45:21 +0000350/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
351/// cases in C where the user forgot to specify the tag.
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000352DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
353 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000354 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
355 LookupName(R, S, false);
356 R.suppressDiagnostics();
357 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000358 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000359 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000360 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000361 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-05-11 21:36:43 +0000362 case TTK_Union: return DeclSpec::TST_union;
363 case TTK_Class: return DeclSpec::TST_class;
364 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000365 }
366 }
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000368 return DeclSpec::TST_unspecified;
369}
370
Francois Pichet48c946e2011-04-13 02:38:49 +0000371/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
372/// if a CXXScopeSpec's type is equal to the type of one of the base classes
373/// then downgrade the missing typename error to a warning.
374/// This is needed for MSVC compatibility; Example:
375/// @code
376/// template<class T> class A {
377/// public:
378/// typedef int TYPE;
379/// };
380/// template<class T> class B : public A<T> {
381/// public:
382/// A<T>::TYPE a; // no typename required because A<T> is a base class.
383/// };
384/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000385bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000386 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000387 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000388
389 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
Aaron Ballman574705e2014-03-13 15:41:46 +0000390 for (const auto &Base : RD->bases())
391 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
Francois Pichet48c946e2011-04-13 02:38:49 +0000392 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000393 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000394 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000395 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000396}
397
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000398bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000399 SourceLocation IILoc,
400 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000401 CXXScopeSpec *SS,
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000402 ParsedType &SuggestedType,
403 bool AllowClassTemplates) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000404 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000405 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000406
Douglas Gregor2d435302009-12-30 17:04:44 +0000407 // There may have been a typo in the name of the type. Look up typo
408 // results, in case we have something that we can suggest.
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000409 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000410 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000411 LookupOrdinaryName, S, SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000412 Validator, CTK_ErrorRecovery)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000413 if (Corrected.isKeyword()) {
414 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000415 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
416 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000417 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000418 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected,
421 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000422 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000423 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
424 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000425 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000426 diagnoseTypo(Corrected,
427 PDiag(diag::err_unknown_nested_typename_suggest)
428 << II << DC << DroppedSpecifier << SS->getRange());
429 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000430 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000431 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000432
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000433 CXXScopeSpec tmpSS;
434 if (Corrected.getCorrectionSpecifier())
435 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
436 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000437 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000438 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
439 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000440 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000441 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000442 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000443 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000444 }
445
David Blaikiebbafb8a2012-03-11 07:00:24 +0000446 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000447 // See if II is a class template that the user forgot to pass arguments to.
448 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000449 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000450 CXXScopeSpec EmptySS;
451 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000452 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000453 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000454 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000455 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000456 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000457 Diag(IILoc, diag::err_template_missing_args) << TplName;
458 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
459 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
460 << TplDecl->getTemplateParameters()->getSourceRange();
461 }
462 return true;
463 }
464 }
465
Douglas Gregor15e56022009-10-13 23:27:22 +0000466 // FIXME: Should we move the logic that tries to recover from a missing tag
467 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
468
Douglas Gregor2d435302009-12-30 17:04:44 +0000469 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000470 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000471 else if (DeclContext *DC = computeDeclContext(*SS, false))
472 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000473 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000474 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000475 unsigned DiagID = diag::err_typename_missing;
Alp Tokerbfa39342014-01-14 12:51:41 +0000476 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000477 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000478
479 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000480 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000481 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000482 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000483 SuggestedType = ActOnTypenameType(S, SourceLocation(),
484 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000485 } else {
486 assert(SS && SS->isInvalid() &&
487 "Invalid scope specifier has already been diagnosed");
488 }
489
490 return true;
491}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000492
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000493/// \brief Determine whether the given result set contains either a type name
494/// or
495static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000496 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000497 NextToken.is(tok::less);
498
499 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
500 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
501 return true;
502
503 if (CheckTemplate && isa<TemplateDecl>(*I))
504 return true;
505 }
506
507 return false;
508}
509
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000510static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
511 Scope *S, CXXScopeSpec &SS,
512 IdentifierInfo *&Name,
513 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000514 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
515 SemaRef.LookupParsedName(R, S, &SS);
516 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000517 const char *TagName = 0;
518 const char *FixItTagName = 0;
519 switch (Tag->getTagKind()) {
520 case TTK_Class:
521 TagName = "class";
522 FixItTagName = "class ";
523 break;
524
525 case TTK_Enum:
526 TagName = "enum";
527 FixItTagName = "enum ";
528 break;
529
530 case TTK_Struct:
531 TagName = "struct";
532 FixItTagName = "struct ";
533 break;
534
Joao Matosdc86f942012-08-31 18:45:21 +0000535 case TTK_Interface:
536 TagName = "__interface";
537 FixItTagName = "__interface ";
538 break;
539
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000540 case TTK_Union:
541 TagName = "union";
542 FixItTagName = "union ";
543 break;
544 }
545
546 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
547 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
548 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
549
Richard Smithaa31b4b2012-09-06 01:37:56 +0000550 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
551 I != IEnd; ++I)
552 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
553 << Name << TagName;
554
555 // Replace lookup results with just the tag decl.
556 Result.clear(Sema::LookupTagName);
557 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000558 return true;
559 }
560
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000561 return false;
562}
563
Richard Smith4f605af2012-08-18 00:55:03 +0000564/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
565static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
566 QualType T, SourceLocation NameLoc) {
567 ASTContext &Context = S.Context;
568
569 TypeLocBuilder Builder;
570 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
571
572 T = S.getElaboratedType(ETK_None, SS, T);
573 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
574 ElabTL.setElaboratedKeywordLoc(SourceLocation());
575 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
576 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
577}
578
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000579Sema::NameClassification Sema::ClassifyName(Scope *S,
580 CXXScopeSpec &SS,
581 IdentifierInfo *&Name,
582 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000583 const Token &NextToken,
584 bool IsAddressOfOperand,
585 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000586 DeclarationNameInfo NameInfo(Name, NameLoc);
587 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000588
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000589 if (NextToken.is(tok::coloncolon)) {
590 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
591 QualType(), false, SS, 0, false);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000592 }
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000593
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000594 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
595 LookupParsedName(Result, S, &SS, !CurMethod);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000596
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000597 // Perform lookup for Objective-C instance variables (including automatically
598 // synthesized instance variables), if we're in an Objective-C method.
599 // FIXME: This lookup really, really needs to be folded in to the normal
600 // unqualified lookup mechanism.
601 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
602 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000603 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000604 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000605 }
606
607 bool SecondTry = false;
608 bool IsFilteredTemplateName = false;
609
610Corrected:
611 switch (Result.getResultKind()) {
612 case LookupResult::NotFound:
613 // If an unqualified-id is followed by a '(', then we have a function
614 // call.
615 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
616 // In C++, this is an ADL-only call.
617 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000618 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000619 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
620
621 // C90 6.3.2.2:
622 // If the expression that precedes the parenthesized argument list in a
623 // function call consists solely of an identifier, and if no
624 // declaration is visible for this identifier, the identifier is
625 // implicitly declared exactly as if, in the innermost block containing
626 // the function call, the declaration
627 //
628 // extern int identifier ();
629 //
630 // appeared.
631 //
632 // We also allow this in C99 as an extension.
633 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
634 Result.addDecl(D);
635 Result.resolveKind();
636 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
637 }
638 }
639
640 // In C, we first see whether there is a tag type by the same name, in
641 // which case it's likely that the user just forget to write "enum",
642 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000643 if (!getLangOpts().CPlusPlus && !SecondTry &&
644 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
645 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000646 }
647
648 // Perform typo correction to determine if there is another name that is
649 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000650 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000651 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000652 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000653 Result.getLookupKind(), S,
John Thompson2255f2c2014-04-23 12:57:01 +0000654 &SS, *CCC,
655 CTK_ErrorRecovery)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000656 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
657 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000658
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000659 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 NamedDecl *UnderlyingFirstDecl
661 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000662 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000663 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000664 UnqualifiedDiag = diag::err_no_template_suggest;
665 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000666 } else if (UnderlyingFirstDecl &&
667 (isa<TypeDecl>(UnderlyingFirstDecl) ||
668 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
669 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000670 UnqualifiedDiag = diag::err_unknown_typename_suggest;
671 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
672 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000673
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000674 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000675 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000676 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000677 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
678 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000679 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000680 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
681 << Name << computeDeclContext(SS, false)
682 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000683 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000684
685 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000686 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000687
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000688 // Typo correction corrected to a keyword.
689 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000690 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000691
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000692 // Also update the LookupResult...
693 // FIXME: This should probably go away at some point
694 Result.clear();
695 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000696 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000697 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000698
699 // If we found an Objective-C instance variable, let
700 // LookupInObjCMethod build the appropriate expression to
701 // reference the ivar.
702 // FIXME: This is a gross hack.
703 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
704 Result.clear();
705 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000706 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000707 }
708
709 goto Corrected;
710 }
711 }
712
713 // We failed to correct; just fall through and let the parser deal with it.
714 Result.suppressDiagnostics();
715 return NameClassification::Unknown();
716
Abramo Bagnara7945c982012-01-27 09:46:47 +0000717 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000718 // We performed name lookup into the current instantiation, and there were
719 // dependent bases, so we treat this result the same way as any other
720 // dependent nested-name-specifier.
721
722 // C++ [temp.res]p2:
723 // A name used in a template declaration or definition and that is
724 // dependent on a template-parameter is assumed not to name a type
725 // unless the applicable name lookup finds a type name or the name is
726 // qualified by the keyword typename.
727 //
728 // FIXME: If the next token is '<', we might want to ask the parser to
729 // perform some heroics to see if we actually have a
730 // template-argument-list, which would indicate a missing 'template'
731 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000732 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
733 NameInfo, IsAddressOfOperand,
734 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000735 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000736
737 case LookupResult::Found:
738 case LookupResult::FoundOverloaded:
739 case LookupResult::FoundUnresolvedValue:
740 break;
741
742 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000743 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000744 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000745 // C++ [temp.local]p3:
746 // A lookup that finds an injected-class-name (10.2) can result in an
747 // ambiguity in certain cases (for example, if it is found in more than
748 // one base class). If all of the injected-class-names that are found
749 // refer to specializations of the same class template, and if the name
750 // is followed by a template-argument-list, the reference refers to the
751 // class template itself and not a specialization thereof, and is not
752 // ambiguous.
753 //
754 // This filtering can make an ambiguous result into an unambiguous one,
755 // so try again after filtering out template names.
756 FilterAcceptableTemplateNames(Result);
757 if (!Result.isAmbiguous()) {
758 IsFilteredTemplateName = true;
759 break;
760 }
761 }
762
763 // Diagnose the ambiguity and return an error.
764 return NameClassification::Error();
765 }
766
David Blaikiebbafb8a2012-03-11 07:00:24 +0000767 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000768 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
769 // C++ [temp.names]p3:
770 // After name lookup (3.4) finds that a name is a template-name or that
771 // an operator-function-id or a literal- operator-id refers to a set of
772 // overloaded functions any member of which is a function template if
773 // this is followed by a <, the < is always taken as the delimiter of a
774 // template-argument-list and never as the less-than operator.
775 if (!IsFilteredTemplateName)
776 FilterAcceptableTemplateNames(Result);
777
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000778 if (!Result.empty()) {
779 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000780 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000781 TemplateName Template;
782 if (Result.end() - Result.begin() > 1) {
783 IsFunctionTemplate = true;
784 Template = Context.getOverloadedTemplateName(Result.begin(),
785 Result.end());
786 } else {
787 TemplateDecl *TD
788 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
789 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000790 IsVarTemplate = isa<VarTemplateDecl>(TD);
791
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000792 if (SS.isSet() && !SS.isInvalid())
793 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000794 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000795 TD);
796 else
797 Template = TemplateName(TD);
798 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000799
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000800 if (IsFunctionTemplate) {
801 // Function templates always go through overload resolution, at which
802 // point we'll perform the various checks (e.g., accessibility) we need
803 // to based on which function we selected.
804 Result.suppressDiagnostics();
805
806 return NameClassification::FunctionTemplate(Template);
807 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000808
809 return IsVarTemplate ? NameClassification::VarTemplate(Template)
810 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000811 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000812 }
Richard Smith4f605af2012-08-18 00:55:03 +0000813
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000814 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000815 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
816 DiagnoseUseOfDecl(Type, NameLoc);
817 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000818 if (SS.isNotEmpty())
819 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000820 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000821 }
Richard Smith4f605af2012-08-18 00:55:03 +0000822
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000823 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
824 if (!Class) {
825 // FIXME: It's unfortunate that we don't have a Type node for handling this.
826 if (ObjCCompatibleAliasDecl *Alias
827 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
828 Class = Alias->getClassInterface();
829 }
830
831 if (Class) {
832 DiagnoseUseOfDecl(Class, NameLoc);
833
834 if (NextToken.is(tok::period)) {
835 // Interface. <something> is parsed as a property reference expression.
836 // Just return "unknown" as a fall-through for now.
837 Result.suppressDiagnostics();
838 return NameClassification::Unknown();
839 }
840
841 QualType T = Context.getObjCInterfaceType(Class);
842 return ParsedType::make(T);
843 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000844
Richard Smith4f605af2012-08-18 00:55:03 +0000845 // We can have a type template here if we're classifying a template argument.
846 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
847 return NameClassification::TypeTemplate(
848 TemplateName(cast<TemplateDecl>(FirstDecl)));
849
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000850 // Check for a tag type hidden by a non-type decl in a few cases where it
851 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000852 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
853 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000854 (NextIsOp &&
855 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000856 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
857 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
858 DiagnoseUseOfDecl(Type, NameLoc);
859 QualType T = Context.getTypeDeclType(Type);
860 if (SS.isNotEmpty())
861 return buildNestedType(*this, SS, T, NameLoc);
862 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000863 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000864
Richard Smith4f605af2012-08-18 00:55:03 +0000865 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000866 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000867
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000868 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
869 return BuildDeclarationNameExpr(SS, Result, ADL);
870}
871
John McCall5ed6e8f2009-08-18 00:00:49 +0000872// Determines the context to return to after temporarily entering a
873// context. This depends in an unnecessarily complicated way on the
874// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000875DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000876
John McCall5ed6e8f2009-08-18 00:00:49 +0000877 // Functions defined inline within classes aren't parsed until we've
878 // finished parsing the top-level class, so the top-level class is
879 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000880 // A Lambda call operator whose parent is a class must not be treated
881 // as an inline member function. A Lambda can be used legally
882 // either as an in-class member initializer or a default argument. These
883 // are parsed once the class has been marked complete and so the containing
884 // context would be the nested class (when the lambda is defined in one);
885 // If the class is not complete, then the lambda is being used in an
886 // ill-formed fashion (such as to specify the width of a bit-field, or
887 // in an array-bound) - in which case we still want to return the
888 // lexically containing DC (which could be a nested class).
889 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000890 DC = DC->getLexicalParent();
891
892 // A function not defined within a class will always return to its
893 // lexical context.
894 if (!isa<CXXRecordDecl>(DC))
895 return DC;
896
897 // A C++ inline method/friend is parsed *after* the topmost class
898 // it was declared in is fully parsed ("complete"); the topmost
899 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000900 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000901 DC = RD;
902
903 // Return the declaration context of the topmost class the inline method is
904 // declared in.
905 return DC;
906 }
907
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000908 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000909}
910
Douglas Gregor91f84212008-12-11 16:49:14 +0000911void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000912 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000913 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000914 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000915 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000916}
917
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000918void Sema::PopDeclContext() {
919 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000920
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000921 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000922 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000923}
924
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000925/// EnterDeclaratorContext - Used when we must lookup names in the context
926/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000927///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000928void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000929 // C++0x [basic.lookup.unqual]p13:
930 // A name used in the definition of a static data member of class
931 // X (after the qualified-id of the static member) is looked up as
932 // if the name was used in a member function of X.
933 // C++0x [basic.lookup.unqual]p14:
934 // If a variable member of a namespace is defined outside of the
935 // scope of its namespace then any name used in the definition of
936 // the variable member (after the declarator-id) is looked up as
937 // if the definition of the variable member occurred in its
938 // namespace.
939 // Both of these imply that we should push a scope whose context
940 // is the semantic context of the declaration. We can't use
941 // PushDeclContext here because that context is not necessarily
942 // lexically contained in the current context. Fortunately,
943 // the containing scope should have the appropriate information.
944
945 assert(!S->getEntity() && "scope already has entity");
946
947#ifndef NDEBUG
948 Scope *Ancestor = S->getParent();
949 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
950 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
951#endif
952
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000953 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000954 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000955}
956
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000957void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000958 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000959
John McCall6df5fef2009-12-19 10:49:29 +0000960 // Switch back to the lexical context. The safety of this is
961 // enforced by an assert in EnterDeclaratorContext.
962 Scope *Ancestor = S->getParent();
963 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000964 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000965
966 // We don't need to do anything with the scope, which is going to
967 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000968}
969
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000970
971void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +0000972 // We assume that the caller has already called
973 // ActOnReenterTemplateScope so getTemplatedDecl() works.
974 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000975 if (!FD)
976 return;
977
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000978 // Same implementation as PushDeclContext, but enters the context
979 // from the lexical parent, rather than the top-level class.
980 assert(CurContext == FD->getLexicalParent() &&
981 "The next DeclContext should be lexically contained in the current one.");
982 CurContext = FD;
983 S->setEntity(CurContext);
984
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000985 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
986 ParmVarDecl *Param = FD->getParamDecl(P);
987 // If the parameter has an identifier, then add it to the scope
988 if (Param->getIdentifier()) {
989 S->AddDecl(Param);
990 IdResolver.AddDecl(Param);
991 }
992 }
993}
994
995
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000996void Sema::ActOnExitFunctionContext() {
997 // Same implementation as PopDeclContext, but returns to the lexical parent,
998 // rather than the top-level class.
999 assert(CurContext && "DeclContext imbalance!");
1000 CurContext = CurContext->getLexicalParent();
1001 assert(CurContext && "Popped translation unit!");
1002}
1003
1004
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001005/// \brief Determine whether we allow overloading of the function
1006/// PrevDecl with another declaration.
1007///
1008/// This routine determines whether overloading is possible, not
1009/// whether some new function is actually an overload. It will return
1010/// true in C++ (where we can always provide overloads) or, as an
1011/// extension, in C when the previous function is already an
1012/// overloaded function declaration or has the "overloadable"
1013/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001014static bool AllowOverloadingOfFunction(LookupResult &Previous,
1015 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001016 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001017 return true;
1018
John McCall1f82f242009-11-18 22:49:29 +00001019 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020 return true;
1021
John McCall1f82f242009-11-18 22:49:29 +00001022 return (Previous.getResultKind() == LookupResult::Found
1023 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001024}
1025
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001026/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001027void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001028 // Move up the scope chain until we find the nearest enclosing
1029 // non-transparent context. The declaration will be introduced into this
1030 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001031 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001032 S = S->getParent();
1033
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001034 // Add scoped declarations into their context, so that they can be
1035 // found later. Declarations without a context won't be inserted
1036 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001037 if (AddToContext)
1038 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001039
Richard Smith541b38b2013-09-20 01:15:31 +00001040 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1041 // are function-local declarations.
1042 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001043 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001044 D->getLexicalDeclContext()->getRedeclContext()) &&
1045 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001046 return;
1047
1048 // Template instantiations should also not be pushed into scope.
1049 if (isa<FunctionDecl>(D) &&
1050 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001051 return;
1052
John McCall9f3059a2009-10-09 21:13:30 +00001053 // If this replaces anything in the current scope,
1054 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1055 IEnd = IdResolver.end();
1056 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001057 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1058 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001059 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001060
John McCall9f3059a2009-10-09 21:13:30 +00001061 // Should only need to replace one decl.
1062 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001063 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001064 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065
John McCall48871652010-08-21 09:40:31 +00001066 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001067
1068 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1069 // Implicitly-generated labels may end up getting generated in an order that
1070 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1071 // the label at the appropriate place in the identifier chain.
1072 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001073 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001074 if (IDC == CurContext) {
1075 if (!S->isDeclScope(*I))
1076 continue;
1077 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001078 break;
1079 }
1080
Douglas Gregor46c04e72011-03-16 16:39:03 +00001081 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001082 } else {
1083 IdResolver.AddDecl(D);
1084 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001085}
1086
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001087void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1088 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1089 TUScope->AddDecl(D);
1090}
1091
Richard Smith1c34fb72013-08-13 18:18:50 +00001092bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001093 bool AllowInlineNamespace) {
1094 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001095}
1096
John McCallcc14d1f2010-08-24 08:50:51 +00001097Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1098 DeclContext *TargetDC = DC->getPrimaryContext();
1099 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001100 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001101 if (ScopeDC->getPrimaryContext() == TargetDC)
1102 return S;
1103 } while ((S = S->getParent()));
1104
1105 return 0;
1106}
1107
John McCall1f82f242009-11-18 22:49:29 +00001108static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1109 DeclContext*,
1110 ASTContext&);
1111
1112/// Filters out lookup results that don't fall within the given scope
1113/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001114void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001115 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001116 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001117 LookupResult::Filter F = R.makeFilter();
1118 while (F.hasNext()) {
1119 NamedDecl *D = F.next();
1120
Richard Smith72bcaec2013-12-05 04:30:04 +00001121 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001122 continue;
1123
Richard Smith72bcaec2013-12-05 04:30:04 +00001124 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001125 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001126
John McCall1f82f242009-11-18 22:49:29 +00001127 F.erase();
1128 }
1129
1130 F.done();
1131}
1132
1133static bool isUsingDecl(NamedDecl *D) {
1134 return isa<UsingShadowDecl>(D) ||
1135 isa<UnresolvedUsingTypenameDecl>(D) ||
1136 isa<UnresolvedUsingValueDecl>(D);
1137}
1138
1139/// Removes using shadow declarations from the lookup results.
1140static void RemoveUsingDecls(LookupResult &R) {
1141 LookupResult::Filter F = R.makeFilter();
1142 while (F.hasNext())
1143 if (isUsingDecl(F.next()))
1144 F.erase();
1145
1146 F.done();
1147}
1148
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001149/// \brief Check for this common pattern:
1150/// @code
1151/// class S {
1152/// S(const S&); // DO NOT IMPLEMENT
1153/// void operator=(const S&); // DO NOT IMPLEMENT
1154/// };
1155/// @endcode
1156static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1157 // FIXME: Should check for private access too but access is set after we get
1158 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001159 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001160 return false;
1161
1162 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1163 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001164 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1165 return Method->isCopyAssignmentOperator();
1166 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001167}
1168
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001169// We need this to handle
1170//
1171// typedef struct {
1172// void *foo() { return 0; }
1173// } A;
1174//
1175// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1176// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001177// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001178// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001179// Callers should verify at the end of the TU if it D has external linkage or
1180// not.
1181bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1182 const DeclContext *DC = D->getDeclContext();
1183 while (!DC->isTranslationUnit()) {
1184 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1185 if (!RD->hasNameForLinkage())
1186 return true;
1187 }
1188 DC = DC->getParent();
1189 }
1190
Rafael Espindola3ae00052013-05-13 00:12:11 +00001191 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001192}
1193
Eli Friedman5ef21752013-09-10 03:05:56 +00001194// FIXME: This needs to be refactored; some other isInMainFile users want
1195// these semantics.
1196static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1197 if (S.TUKind != TU_Complete)
1198 return false;
1199 return S.SourceMgr.isInMainFile(Loc);
1200}
1201
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001202bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1203 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001204
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1206 return false;
1207
Richard Smithc3926172014-04-02 18:28:36 +00001208 // Ignore all entities declared within templates, and out-of-line definitions
1209 // of members of class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001210 if (D->getDeclContext()->isDependentContext() ||
1211 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001212 return false;
1213
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001214 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001215 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1216 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001217
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001218 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1219 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1220 return false;
1221 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001222 // 'static inline' functions are defined in headers; don't warn.
1223 if (FD->isInlineSpecified() &&
1224 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001225 return false;
1226 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001227
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001228 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001229 Context.DeclMustBeEmitted(FD))
1230 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001231 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001232 // Constants and utility variables are defined in headers with internal
1233 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1234 // like "inline".)
1235 if (!isMainFileLoc(*this, VD->getLocation()))
1236 return false;
1237
Eli Friedman5ef21752013-09-10 03:05:56 +00001238 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001239 return false;
1240
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001241 if (VD->isStaticDataMember() &&
1242 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1243 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001244 } else {
1245 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001246 }
1247
John McCalld37d35b2010-10-27 01:41:35 +00001248 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001249 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001250}
1251
1252void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (!D)
1254 return;
1255
1256 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001257 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001258 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1259 return; // First should already be in the vector.
1260 }
1261
1262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001263 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001264 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1265 return; // First should already be in the vector.
1266 }
1267
David Blaikie3d8edc22012-05-26 05:35:39 +00001268 if (ShouldWarnIfUnusedFileScopedDecl(D))
1269 UnusedFileScopedDecls.push_back(D);
1270}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001271
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001272static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001273 if (D->isInvalidDecl())
1274 return false;
1275
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001276 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1277 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001278 return false;
John McCall67da35c2010-02-04 22:26:26 +00001279
Chris Lattnercab02a62011-02-17 20:34:02 +00001280 if (isa<LabelDecl>(D))
1281 return true;
1282
John McCall67da35c2010-02-04 22:26:26 +00001283 // White-list anything that isn't a local variable.
1284 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1285 !D->getDeclContext()->isFunctionOrMethod())
1286 return false;
1287
1288 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001289 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001290
1291 // White-list anything with an __attribute__((unused)) type.
1292 QualType Ty = VD->getType();
1293
1294 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001295 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001296 if (TT->getDecl()->hasAttr<UnusedAttr>())
1297 return false;
1298 }
1299
Douglas Gregor14f232e2010-05-08 23:05:03 +00001300 // If we failed to complete the type for some reason, or if the type is
1301 // dependent, don't diagnose the variable.
1302 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001303 return false;
1304
John McCallcef15822010-03-31 02:47:45 +00001305 if (const TagType *TT = Ty->getAs<TagType>()) {
1306 const TagDecl *Tag = TT->getDecl();
1307 if (Tag->hasAttr<UnusedAttr>())
1308 return false;
1309
1310 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001311 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001312 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001313
1314 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001315 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1316 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001317 const CXXConstructExpr *Construct =
1318 dyn_cast<CXXConstructExpr>(Init);
1319 if (Construct && !Construct->isElidable()) {
1320 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001321 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001322 return false;
1323 }
1324 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001325 }
1326 }
John McCallcef15822010-03-31 02:47:45 +00001327
1328 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001329 }
1330
John McCall67da35c2010-02-04 22:26:26 +00001331 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001332}
1333
Anna Zaks964f4c62011-07-28 20:52:06 +00001334static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1335 FixItHint &Hint) {
1336 if (isa<LabelDecl>(D)) {
1337 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001338 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001339 if (AfterColon.isInvalid())
1340 return;
1341 Hint = FixItHint::CreateRemoval(CharSourceRange::
1342 getCharRange(D->getLocStart(), AfterColon));
1343 }
1344 return;
1345}
1346
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001347/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1348/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001349void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001350 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001351 if (!ShouldDiagnoseUnusedDecl(D))
1352 return;
1353
Anna Zaks964f4c62011-07-28 20:52:06 +00001354 GenerateFixForUnusedDecl(D, Context, Hint);
1355
Chris Lattnercab02a62011-02-17 20:34:02 +00001356 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001357 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001358 DiagID = diag::warn_unused_exception_param;
1359 else if (isa<LabelDecl>(D))
1360 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001361 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001362 DiagID = diag::warn_unused_variable;
1363
Anna Zaks964f4c62011-07-28 20:52:06 +00001364 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001365}
1366
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001367static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1368 // Verify that we have no forward references left. If so, there was a goto
1369 // or address of a label taken, but no definition of it. Label fwd
1370 // definitions are indicated with a null substmt.
1371 if (L->getStmt() == 0)
1372 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1373}
1374
Steve Naroffc62adb62007-10-09 22:01:59 +00001375void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001376 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001377 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001378 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001379
Aaron Ballman35c54952014-03-17 16:55:25 +00001380 for (auto *TmpD : S->decls()) {
Steve Naroff9324db12007-09-13 18:10:37 +00001381 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001382
Douglas Gregor91f84212008-12-11 16:49:14 +00001383 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1384 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001385
Douglas Gregor91f84212008-12-11 16:49:14 +00001386 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001387
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001388 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001389 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001390 DiagnoseUnusedDecl(D);
1391
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001392 // If this was a forward reference to a label, verify it was defined.
1393 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1394 CheckPoppedLabel(LD, *this);
1395
Douglas Gregor91f84212008-12-11 16:49:14 +00001396 // Remove this name from our lexical scope.
1397 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001398 }
1399}
1400
Douglas Gregor1c283312010-08-11 12:19:30 +00001401/// \brief Look for an Objective-C class in the translation unit.
1402///
1403/// \param Id The name of the Objective-C class we're looking for. If
1404/// typo-correction fixes this name, the Id will be updated
1405/// to the fixed name.
1406///
1407/// \param IdLoc The location of the name in the translation unit.
1408///
James Dennett41725122012-06-22 10:16:05 +00001409/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001410/// if there is no class with the given name.
1411///
1412/// \returns The declaration of the named Objective-C class, or NULL if the
1413/// class could not be found.
1414ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1415 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001416 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001417 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1418 // creation from this context.
1419 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1420
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001421 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001422 // Perform typo correction at the given location, but only if we
1423 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001424 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1425 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1426 LookupOrdinaryName, TUScope, NULL,
John Thompson2255f2c2014-04-23 12:57:01 +00001427 Validator, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001428 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001429 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001430 Id = IDecl->getIdentifier();
1431 }
1432 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001433 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1434 // This routine must always return a class definition, if any.
1435 if (Def && Def->getDefinition())
1436 Def = Def->getDefinition();
1437 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001438}
1439
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001440/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1441/// from S, where a non-field would be declared. This routine copes
1442/// with the difference between C and C++ scoping rules in structs and
1443/// unions. For example, the following code is well-formed in C but
1444/// ill-formed in C++:
1445/// @code
1446/// struct S6 {
1447/// enum { BAR } e;
1448/// };
Mike Stump11289f42009-09-09 15:08:12 +00001449///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001450/// void test_S6() {
1451/// struct S6 a;
1452/// a.e = BAR;
1453/// }
1454/// @endcode
1455/// For the declaration of BAR, this routine will return a different
1456/// scope. The scope S will be the scope of the unnamed enumeration
1457/// within S6. In C++, this routine will return the scope associated
1458/// with S6, because the enumeration's scope is a transparent
1459/// context but structures can contain non-field names. In C, this
1460/// routine will return the translation unit scope, since the
1461/// enumeration's scope is a transparent context and structures cannot
1462/// contain non-field names.
1463Scope *Sema::getNonFieldDeclScope(Scope *S) {
1464 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001465 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001466 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001467 S = S->getParent();
1468 return S;
1469}
1470
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001471/// \brief Looks up the declaration of "struct objc_super" and
1472/// saves it for later use in building builtin declaration of
1473/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1474/// pre-existing declaration exists no action takes place.
1475static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1476 IdentifierInfo *II) {
1477 if (!II->isStr("objc_msgSendSuper"))
1478 return;
1479 ASTContext &Context = ThisSema.Context;
1480
1481 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1482 SourceLocation(), Sema::LookupTagName);
1483 ThisSema.LookupName(Result, S);
1484 if (Result.getResultKind() == LookupResult::Found)
1485 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1486 Context.setObjCSuperType(Context.getTagDeclType(TD));
1487}
1488
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001489/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1490/// file scope. lazily create a decl for it. ForRedeclaration is true
1491/// if we're creating this built-in in anticipation of redeclaring the
1492/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001493NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001494 Scope *S, bool ForRedeclaration,
1495 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001496 LookupPredefedObjCSuperType(*this, S, II);
1497
Chris Lattner9561a0b2007-01-28 08:20:04 +00001498 Builtin::ID BID = (Builtin::ID)bid;
1499
Chris Lattnerecd79c62009-06-14 00:45:47 +00001500 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001501 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001502 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001503 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001504 // Okay
1505 break;
1506
Mike Stump93246cc2009-07-28 23:57:15 +00001507 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001508 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001509 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001510 << Context.BuiltinInfo.GetName(BID);
1511 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001512
Mike Stump93246cc2009-07-28 23:57:15 +00001513 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001514 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001515 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001516 << Context.BuiltinInfo.GetName(BID);
1517 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001518
1519 case ASTContext::GE_Missing_ucontext:
1520 if (ForRedeclaration)
1521 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1522 << Context.BuiltinInfo.GetName(BID);
1523 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001524 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001525
1526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1527 Diag(Loc, diag::ext_implicit_lib_function_decl)
1528 << Context.BuiltinInfo.GetName(BID)
1529 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001530 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001532 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001533 Diag(Loc, diag::note_please_include_header)
1534 << Context.BuiltinInfo.getHeaderName(BID)
1535 << Context.BuiltinInfo.GetName(BID);
1536 }
1537
Warren Hunt445d83e2013-11-01 23:46:51 +00001538 DeclContext *Parent = Context.getTranslationUnitDecl();
1539 if (getLangOpts().CPlusPlus) {
1540 LinkageSpecDecl *CLinkageDecl =
1541 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1542 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001543 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001544 Parent->addDecl(CLinkageDecl);
1545 Parent = CLinkageDecl;
1546 }
1547
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001548 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001549 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001550 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001551 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001552 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001553 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001554 New->setImplicit();
1555
Chris Lattner4dd27102008-05-05 22:18:14 +00001556 // Create Decl objects for each parameter, adding them to the
1557 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001558 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001559 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001560 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001561 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001562 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1563 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001564 parm->setScopeInfo(0, i);
1565 Params.push_back(parm);
1566 }
David Blaikie9c70e042011-09-21 18:16:56 +00001567 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
1570 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001571 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001573 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001574 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1575 // relate Scopes to DeclContexts, and probably eliminate CurContext
1576 // entirely, but we're not there yet.
1577 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001578 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001579 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001580 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001581 return New;
1582}
1583
Douglas Gregor3552dab2013-01-09 00:47:56 +00001584/// \brief Filter out any previous declarations that the given declaration
1585/// should not consider because they are not permitted to conflict, e.g.,
1586/// because they come from hidden sub-modules and do not refer to the same
1587/// entity.
1588static void filterNonConflictingPreviousDecls(ASTContext &context,
1589 NamedDecl *decl,
1590 LookupResult &previous){
1591 // This is only interesting when modules are enabled.
1592 if (!context.getLangOpts().Modules)
1593 return;
1594
1595 // Empty sets are uninteresting.
1596 if (previous.empty())
1597 return;
1598
Douglas Gregor3552dab2013-01-09 00:47:56 +00001599 LookupResult::Filter filter = previous.makeFilter();
1600 while (filter.hasNext()) {
1601 NamedDecl *old = filter.next();
1602
1603 // Non-hidden declarations are never ignored.
1604 if (!old->isHidden())
1605 continue;
1606
Rafael Espindola3ae00052013-05-13 00:12:11 +00001607 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001608 filter.erase();
1609 }
1610
1611 filter.done();
1612}
1613
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001614bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1615 QualType OldType;
1616 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1617 OldType = OldTypedef->getUnderlyingType();
1618 else
1619 OldType = Context.getTypeDeclType(Old);
1620 QualType NewType = New->getUnderlyingType();
1621
Douglas Gregoraab36982012-01-11 22:33:48 +00001622 if (NewType->isVariablyModifiedType()) {
1623 // Must not redefine a typedef with a variably-modified type.
1624 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1625 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1626 << Kind << NewType;
1627 if (Old->getLocation().isValid())
1628 Diag(Old->getLocation(), diag::note_previous_definition);
1629 New->setInvalidDecl();
1630 return true;
1631 }
1632
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001633 if (OldType != NewType &&
1634 !OldType->isDependentType() &&
1635 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001636 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1638 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1639 << Kind << NewType << OldType;
1640 if (Old->getLocation().isValid())
1641 Diag(Old->getLocation(), diag::note_previous_definition);
1642 New->setInvalidDecl();
1643 return true;
1644 }
1645 return false;
1646}
1647
Richard Smithdda56e42011-04-15 14:24:37 +00001648/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001649/// same name and scope as a previous declaration 'Old'. Figure out
1650/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001651/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001652///
Richard Smithdda56e42011-04-15 14:24:37 +00001653void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001654 // If the new decl is known invalid already, don't bother doing any
1655 // merging checks.
1656 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001657
Steve Naroff44cfcb62008-09-09 14:32:20 +00001658 // Allow multiple definitions for ObjC built-in typedefs.
1659 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001661 const IdentifierInfo *TypeID = New->getIdentifier();
1662 switch (TypeID->getLength()) {
1663 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001664 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001665 {
1666 if (!TypeID->isStr("id"))
1667 break;
1668 QualType T = New->getUnderlyingType();
1669 if (!T->isPointerType())
1670 break;
1671 if (!T->isVoidPointerType()) {
1672 QualType PT = T->getAs<PointerType>()->getPointeeType();
1673 if (!PT->isStructureType())
1674 break;
1675 }
1676 Context.setObjCIdRedefinitionType(T);
1677 // Install the built-in type for 'id', ignoring the current definition.
1678 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1679 return;
1680 }
Chris Lattner66e32812008-11-20 05:41:43 +00001681 case 5:
1682 if (!TypeID->isStr("Class"))
1683 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001684 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001685 // Install the built-in type for 'Class', ignoring the current definition.
1686 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001687 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001688 case 3:
1689 if (!TypeID->isStr("SEL"))
1690 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001691 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001692 // Install the built-in type for 'SEL', ignoring the current definition.
1693 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001694 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001695 }
1696 // Fall through - the typedef name was not a builtin type.
1697 }
John McCall1f82f242009-11-18 22:49:29 +00001698
Douglas Gregorfb034662009-01-28 17:15:10 +00001699 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001700 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1701 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001702 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001703 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001704
1705 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001706 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001707 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001708
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001709 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001710 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001711
John McCall1f82f242009-11-18 22:49:29 +00001712 // If the old declaration is invalid, just give up here.
1713 if (Old->isInvalidDecl())
1714 return New->setInvalidDecl();
1715
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001716 // If the typedef types are not identical, reject them in all languages and
1717 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001718 if (isIncompatibleTypedef(Old, New))
1719 return;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001721 // The types match. Link up the redeclaration chain and merge attributes if
1722 // the old declaration was a typedef.
1723 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001724 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001725 mergeDeclAttributes(New, Old);
1726 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001727
David Blaikiebbafb8a2012-03-11 07:00:24 +00001728 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001729 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001730
David Blaikiebbafb8a2012-03-11 07:00:24 +00001731 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001732 // C++ [dcl.typedef]p2:
1733 // In a given non-class scope, a typedef specifier can be used to
1734 // redefine the name of any type declared in that scope to refer
1735 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001736 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001737 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001738
1739 // C++0x [dcl.typedef]p4:
1740 // In a given class scope, a typedef specifier can be used to redefine
1741 // any class-name declared in that scope that is not also a typedef-name
1742 // to refer to the type to which it already refers.
1743 //
1744 // This wording came in via DR424, which was a correction to the
1745 // wording in DR56, which accidentally banned code like:
1746 //
1747 // struct S {
1748 // typedef struct A { } A;
1749 // };
1750 //
1751 // in the C++03 standard. We implement the C++0x semantics, which
1752 // allow the above but disallow
1753 //
1754 // struct S {
1755 // typedef int I;
1756 // typedef int I;
1757 // };
1758 //
1759 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001760 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001761 return;
1762
Chris Lattner2581fc32009-04-17 22:04:20 +00001763 Diag(New->getLocation(), diag::err_redefinition)
1764 << New->getDeclName();
1765 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001766 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001767 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001768
Douglas Gregor7363fb02012-01-11 04:25:01 +00001769 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001770 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001771 return;
1772
Chris Lattner2581fc32009-04-17 22:04:20 +00001773 // If we have a redefinition of a typedef in C, emit a warning. This warning
1774 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001775 // -Wtypedef-redefinition. If either the original or the redefinition is
1776 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001777 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001778 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1779 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001780 return;
Mike Stump11289f42009-09-09 15:08:12 +00001781
Chris Lattner2581fc32009-04-17 22:04:20 +00001782 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1783 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001784 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001785 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001786}
1787
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001788/// DeclhasAttr - returns true if decl Declaration already has the target
1789/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001790static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001791 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001792 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001793 for (const auto *i : D->attrs())
1794 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001795 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001796 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001797 return true;
1798 continue;
1799 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001800 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001801 if (OA && isa<OwnershipAttr>(i))
1802 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001803 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001804 }
Chris Lattner84966392008-03-03 03:28:21 +00001805
1806 return false;
1807}
1808
Richard Smithbc8caaf2013-02-22 04:55:39 +00001809static bool isAttributeTargetADefinition(Decl *D) {
1810 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1811 return VD->isThisDeclarationADefinition();
1812 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1813 return TD->isCompleteDefinition() || TD->isBeingDefined();
1814 return true;
1815}
1816
1817/// Merge alignment attributes from \p Old to \p New, taking into account the
1818/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1819///
1820/// \return \c true if any attributes were added to \p New.
1821static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1822 // Look for alignas attributes on Old, and pick out whichever attribute
1823 // specifies the strictest alignment requirement.
1824 AlignedAttr *OldAlignasAttr = 0;
1825 AlignedAttr *OldStrictestAlignAttr = 0;
1826 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001827 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001828 // FIXME: We have no way of representing inherited dependent alignments
1829 // in a case like:
1830 // template<int A, int B> struct alignas(A) X;
1831 // template<int A, int B> struct alignas(B) X {};
1832 // For now, we just ignore any alignas attributes which are not on the
1833 // definition in such a case.
1834 if (I->isAlignmentDependent())
1835 return false;
1836
1837 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001838 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001839
1840 unsigned Align = I->getAlignment(S.Context);
1841 if (Align > OldAlign) {
1842 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001843 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001844 }
1845 }
1846
1847 // Look for alignas attributes on New.
1848 AlignedAttr *NewAlignasAttr = 0;
1849 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001850 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001851 if (I->isAlignmentDependent())
1852 return false;
1853
1854 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001855 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001856
1857 unsigned Align = I->getAlignment(S.Context);
1858 if (Align > NewAlign)
1859 NewAlign = Align;
1860 }
1861
1862 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1863 // Both declarations have 'alignas' attributes. We require them to match.
1864 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1865 // fall short. (If two declarations both have alignas, they must both match
1866 // every definition, and so must match each other if there is a definition.)
1867
1868 // If either declaration only contains 'alignas(0)' specifiers, then it
1869 // specifies the natural alignment for the type.
1870 if (OldAlign == 0 || NewAlign == 0) {
1871 QualType Ty;
1872 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1873 Ty = VD->getType();
1874 else
1875 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1876
1877 if (OldAlign == 0)
1878 OldAlign = S.Context.getTypeAlign(Ty);
1879 if (NewAlign == 0)
1880 NewAlign = S.Context.getTypeAlign(Ty);
1881 }
1882
1883 if (OldAlign != NewAlign) {
1884 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1885 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1886 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1887 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1888 }
1889 }
1890
1891 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1892 // C++11 [dcl.align]p6:
1893 // if any declaration of an entity has an alignment-specifier,
1894 // every defining declaration of that entity shall specify an
1895 // equivalent alignment.
1896 // C11 6.7.5/7:
1897 // If the definition of an object does not have an alignment
1898 // specifier, any other declaration of that object shall also
1899 // have no alignment specifier.
1900 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001901 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001902 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001903 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001904 }
1905
1906 bool AnyAdded = false;
1907
1908 // Ensure we have an attribute representing the strictest alignment.
1909 if (OldAlign > NewAlign) {
1910 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1911 Clone->setInherited(true);
1912 New->addAttr(Clone);
1913 AnyAdded = true;
1914 }
1915
1916 // Ensure we have an alignas attribute if the old declaration had one.
1917 if (OldAlignasAttr && !NewAlignasAttr &&
1918 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1919 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1920 Clone->setInherited(true);
1921 New->addAttr(Clone);
1922 AnyAdded = true;
1923 }
1924
1925 return AnyAdded;
1926}
1927
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001928static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
1929 const InheritableAttr *Attr, bool Override) {
1930 InheritableAttr *NewAttr = nullptr;
Michael Han99315932013-01-24 16:46:58 +00001931 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001932 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001933 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1934 AA->getIntroduced(), AA->getDeprecated(),
1935 AA->getObsoleted(), AA->getUnavailable(),
1936 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001937 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001938 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001939 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1940 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001941 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001942 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1943 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001944 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001945 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1946 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001947 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001948 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1949 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001950 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001951 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1952 FA->getFormatIdx(), FA->getFirstArg(),
1953 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001954 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001955 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1956 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001957 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00001958 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1959 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00001960 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00001961 else if (isa<AlignedAttr>(Attr))
1962 // AlignedAttrs are handled separately, because we need to handle all
1963 // such attributes on a declaration at the same time.
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001964 NewAttr = nullptr;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001965 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001966 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001967
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001968 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001969 NewAttr->setInherited(true);
1970 D->addAttr(NewAttr);
1971 return true;
1972 }
1973
1974 return false;
1975}
1976
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001977static const Decl *getDefinition(const Decl *D) {
1978 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001979 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001980 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1981 const VarDecl *Def = VD->getDefinition();
1982 if (Def)
1983 return Def;
1984 return VD->getActingDefinition();
1985 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001986 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001987 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001988 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001989 return Def;
1990 }
1991 return NULL;
1992}
1993
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001994static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001995 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001996 if (Attribute->getKind() == Kind)
1997 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001998 return false;
1999}
2000
2001/// checkNewAttributesAfterDef - If we already have a definition, check that
2002/// there are no new attributes in this declaration.
2003static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2004 if (!New->hasAttrs())
2005 return;
2006
2007 const Decl *Def = getDefinition(Old);
2008 if (!Def || Def == New)
2009 return;
2010
2011 AttrVec &NewAttributes = New->getAttrs();
2012 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2013 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002014
2015 if (isa<AliasAttr>(NewAttribute)) {
2016 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2017 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2018 else {
2019 VarDecl *VD = cast<VarDecl>(New);
2020 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2021 VarDecl::TentativeDefinition
2022 ? diag::err_alias_after_tentative
2023 : diag::err_redefinition;
2024 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2025 S.Diag(Def->getLocation(), diag::note_previous_definition);
2026 VD->setInvalidDecl();
2027 }
2028 ++I;
2029 continue;
2030 }
2031
2032 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2033 // Tentative definitions are only interesting for the alias check above.
2034 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2035 ++I;
2036 continue;
2037 }
2038 }
2039
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002040 if (hasAttribute(Def, NewAttribute->getKind())) {
2041 ++I;
2042 continue; // regular attr merging will take care of validating this.
2043 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002044
Richard Smithdebc59d2013-01-30 05:45:05 +00002045 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002046 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002047 ++I;
2048 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002049 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2050 if (AA->isAlignas()) {
2051 // C++11 [dcl.align]p6:
2052 // if any declaration of an entity has an alignment-specifier,
2053 // every defining declaration of that entity shall specify an
2054 // equivalent alignment.
2055 // C11 6.7.5/7:
2056 // If the definition of an object does not have an alignment
2057 // specifier, any other declaration of that object shall also
2058 // have no alignment specifier.
2059 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002060 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002061 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002062 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002063 NewAttributes.erase(NewAttributes.begin() + I);
2064 --E;
2065 continue;
2066 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002067 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002068
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002069 S.Diag(NewAttribute->getLocation(),
2070 diag::warn_attribute_precede_definition);
2071 S.Diag(Def->getLocation(), diag::note_previous_definition);
2072 NewAttributes.erase(NewAttributes.begin() + I);
2073 --E;
2074 }
2075}
2076
John McCallf79e87d2011-03-02 04:00:57 +00002077/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002078void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002079 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002080 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2081 UsedAttr *NewAttr = OldAttr->clone(Context);
2082 NewAttr->setInherited(true);
2083 New->addAttr(NewAttr);
2084 }
2085
Richard Smithe233fbf2013-01-28 22:42:45 +00002086 if (!Old->hasAttrs() && !New->hasAttrs())
2087 return;
2088
Rafael Espindola36191042012-05-18 01:47:00 +00002089 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002090 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002091
Douglas Gregor32c17572012-01-01 20:30:41 +00002092 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002093 return;
John McCallf79e87d2011-03-02 04:00:57 +00002094
Douglas Gregor32c17572012-01-01 20:30:41 +00002095 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002096
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002097 // Ensure that any moving of objects within the allocated map is done before
2098 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002099 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002100
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002101 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002102 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002103 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002104 if (isa<DeprecatedAttr>(I) ||
2105 isa<UnavailableAttr>(I) ||
2106 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002107 switch (AMK) {
2108 case AMK_None:
2109 continue;
John McCalld2930c22011-07-22 02:45:48 +00002110
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002111 case AMK_Redeclaration:
2112 break;
2113
2114 case AMK_Override:
2115 Override = true;
2116 break;
2117 }
2118 }
2119
Rafael Espindolab0938852013-10-25 01:28:12 +00002120 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002121 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002122 continue;
2123
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002124 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002125 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002126 }
John McCallf79e87d2011-03-02 04:00:57 +00002127
Richard Smithbc8caaf2013-02-22 04:55:39 +00002128 if (mergeAlignedAttrs(*this, New, Old))
2129 foundAny = true;
2130
Douglas Gregor32c17572012-01-01 20:30:41 +00002131 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002132}
2133
2134/// mergeParamDeclAttributes - Copy attributes from the old parameter
2135/// to the new one.
2136static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2137 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002138 Sema &S) {
2139 // C++11 [dcl.attr.depend]p2:
2140 // The first declaration of a function shall specify the
2141 // carries_dependency attribute for its declarator-id if any declaration
2142 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002143 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2144 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2145 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002146 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2147 // Find the first declaration of the parameter.
2148 // FIXME: Should we build redeclaration chains for function parameters?
2149 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002150 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002151 const ParmVarDecl *FirstVD =
2152 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2153 S.Diag(FirstVD->getLocation(),
2154 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2155 }
2156
John McCallf79e87d2011-03-02 04:00:57 +00002157 if (!oldDecl->hasAttrs())
2158 return;
2159
2160 bool foundAny = newDecl->hasAttrs();
2161
2162 // Ensure that any moving of objects within the allocated map is
2163 // done before we process them.
2164 if (!foundAny) newDecl->setAttrs(AttrVec());
2165
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002166 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2167 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002168 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002169 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002170 newAttr->setInherited(true);
2171 newDecl->addAttr(newAttr);
2172 foundAny = true;
2173 }
2174 }
2175
2176 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002177}
2178
Dan Gohman28ade552010-07-26 21:25:24 +00002179namespace {
2180
Douglas Gregora74a2972009-03-06 22:43:54 +00002181/// Used in MergeFunctionDecl to keep track of function parameters in
2182/// C.
2183struct GNUCompatibleParamWarning {
2184 ParmVarDecl *OldParm;
2185 ParmVarDecl *NewParm;
2186 QualType PromotedType;
2187};
2188
Dan Gohman28ade552010-07-26 21:25:24 +00002189}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002190
2191/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002192Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002193 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002194 if (Ctor->isDefaultConstructor())
2195 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002196
2197 if (Ctor->isCopyConstructor())
2198 return Sema::CXXCopyConstructor;
2199
2200 if (Ctor->isMoveConstructor())
2201 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002202 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002203 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002204 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002205 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002206 } else if (MD->isMoveAssignmentOperator()) {
2207 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002208 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002209
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002210 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002211}
2212
Sebastian Redl243d9052010-06-09 21:17:41 +00002213/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002214/// only extern inline functions can be redefined, and even then only in
2215/// GNU89 mode.
2216static bool canRedefineFunction(const FunctionDecl *FD,
2217 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002218 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2219 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002220 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002221 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002222}
2223
Reid Kleckner78af0702013-08-27 23:08:25 +00002224const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2225 const AttributedType *AT = T->getAs<AttributedType>();
2226 while (AT && !AT->isCallingConv())
2227 AT = AT->getModifiedType()->getAs<AttributedType>();
2228 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002229}
2230
Benjamin Kramer3e350262013-02-15 12:30:38 +00002231template <typename T>
2232static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002233 const DeclContext *DC = Old->getDeclContext();
2234 if (DC->isRecord())
2235 return false;
2236
2237 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002238 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002239 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002240 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002241 return true;
2242 return false;
2243}
2244
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002245/// MergeFunctionDecl - We just parsed a function 'New' from
2246/// declarator D which has the same name and scope as a previous
2247/// declaration 'Old'. Figure out how to resolve this situation,
2248/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002249///
2250/// In C++, New and Old must be declarations that are not
2251/// overloaded. Use IsOverload to determine whether New and Old are
2252/// overloaded, and to select the Old declaration that New should be
2253/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002254///
2255/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002256bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2257 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002258 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002259 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002260 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002261 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002262 if (New->getFriendObjectKind()) {
2263 Diag(New->getLocation(), diag::err_using_decl_friend);
2264 Diag(Shadow->getTargetDecl()->getLocation(),
2265 diag::note_using_decl_target);
2266 Diag(Shadow->getUsingDecl()->getLocation(),
2267 diag::note_using_decl) << 0;
2268 return true;
2269 }
2270
Richard Smith18819302014-02-06 01:31:33 +00002271 // C++11 [namespace.udecl]p14:
2272 // If a function declaration in namespace scope or block scope has the
2273 // same name and the same parameter-type-list as a function introduced
2274 // by a using-declaration, and the declarations do not declare the same
2275 // function, the program is ill-formed.
2276
2277 // Check whether the two declarations might declare the same function.
2278 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2279 if (Old &&
2280 !Old->getDeclContext()->getRedeclContext()->Equals(
2281 New->getDeclContext()->getRedeclContext()) &&
2282 !(Old->isExternC() && New->isExternC()))
2283 Old = 0;
2284
2285 if (!Old) {
2286 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2287 Diag(Shadow->getTargetDecl()->getLocation(),
2288 diag::note_using_decl_target);
2289 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2290 return true;
2291 }
2292 OldD = Old;
2293 } else {
2294 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2295 << New->getDeclName();
2296 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002297 return true;
2298 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002300
David Majnemerea5092a2013-07-07 23:49:50 +00002301 // If the old declaration is invalid, just give up here.
2302 if (Old->isInvalidDecl())
2303 return true;
2304
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002305 // Determine whether the previous declaration was a definition,
2306 // implicit declaration, or a declaration.
2307 diag::kind PrevDiag;
Richard Smithbdd14642014-02-04 01:14:30 +00002308 SourceLocation OldLocation = Old->getLocation();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002309 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002310 PrevDiag = diag::note_previous_definition;
Richard Smithbdd14642014-02-04 01:14:30 +00002311 else if (Old->isImplicit()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002312 PrevDiag = diag::note_previous_implicit_declaration;
Richard Smithbdd14642014-02-04 01:14:30 +00002313 if (OldLocation.isInvalid())
2314 OldLocation = New->getLocation();
2315 } else
Chris Lattner0369c572008-11-23 23:12:31 +00002316 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Charles Davisfea48452010-02-18 02:00:42 +00002318 // Don't complain about this if we're in GNU89 mode and the old function
2319 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002320 // Don't complain about specializations. They are not supposed to have
2321 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002322 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002323 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002324 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002325 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002326 !canRedefineFunction(Old, getLangOpts())) {
2327 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002328 Diag(New->getLocation(), diag::warn_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002329 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002330 } else {
2331 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002332 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002333 return true;
2334 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002335 }
2336
Reid Kleckner78af0702013-08-27 23:08:25 +00002337
2338 // If a function is first declared with a calling convention, but is later
2339 // declared or defined without one, all following decls assume the calling
2340 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002341 //
John McCalla5f46fb2012-08-25 02:00:03 +00002342 // It's OK if a function is first declared without a calling convention,
2343 // but is later declared or defined with the default calling convention.
2344 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002345 // To test if either decl has an explicit calling convention, we look for
2346 // AttributedType sugar nodes on the type as written. If they are missing or
2347 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002348 //
2349 // Note also that we DO NOT return at this point, because we still have
2350 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002351 QualType OldQType = Context.getCanonicalType(Old->getType());
2352 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002353 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002354 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002355 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2356 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2357 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002358
Reid Kleckner78af0702013-08-27 23:08:25 +00002359 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002360 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002361 const FunctionType *FT =
2362 First->getType().getCanonicalType()->castAs<FunctionType>();
2363 FunctionType::ExtInfo FI = FT->getExtInfo();
2364 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2365 if (!NewCCExplicit) {
2366 // Inherit the CC from the previous declaration if it was specified
2367 // there but not here.
2368 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2369 RequiresAdjustment = true;
2370 } else {
2371 // Calling conventions aren't compatible, so complain.
2372 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2373 Diag(New->getLocation(), diag::err_cconv_change)
2374 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2375 << !FirstCCExplicit
2376 << (!FirstCCExplicit ? "" :
2377 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002378
Reid Kleckner78af0702013-08-27 23:08:25 +00002379 // Put the note on the first decl, since it is the one that matters.
2380 Diag(First->getLocation(), diag::note_previous_declaration);
2381 return true;
2382 }
John McCallcddbad02010-02-04 05:44:44 +00002383 }
2384
John McCallab26cfa2010-02-05 21:31:56 +00002385 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002386 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2387 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2388 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002389 }
2390
Douglas Gregor77e274f2010-06-18 21:30:25 +00002391 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002392 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2393 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2394 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002395 Diag(New->getLocation(), diag::err_regparm_mismatch)
2396 << NewType->getRegParmType()
2397 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002398 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002399 return true;
2400 }
John McCall4f5019e2010-12-19 02:44:49 +00002401
2402 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2403 RequiresAdjustment = true;
2404 }
2405
Douglas Gregorf1404d72011-10-14 15:55:40 +00002406 // Merge ns_returns_retained attribute.
2407 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2408 if (NewTypeInfo.getProducesResult()) {
2409 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002410 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002411 return true;
2412 }
2413
2414 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2415 RequiresAdjustment = true;
2416 }
2417
John McCall4f5019e2010-12-19 02:44:49 +00002418 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002419 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2420 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2421 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002422 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002423 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002424 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002425
2426 // If this redeclaration makes the function inline, we may need to add it to
2427 // UndefinedButUsed.
2428 if (!Old->isInlined() && New->isInlined() &&
2429 !New->hasAttr<GNUInlineAttr>() &&
2430 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2431 Old->isUsed(false) &&
2432 !Old->isDefined() && !New->isThisDeclarationADefinition())
2433 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2434 SourceLocation()));
2435
2436 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2437 // about it.
2438 if (New->hasAttr<GNUInlineAttr>() &&
2439 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2440 UndefinedButUsed.erase(Old->getCanonicalDecl());
2441 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002442
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002444 // (C++98 13.1p2):
2445 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002446 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002447 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002448
2449 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002450 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002451 // Redeclarations or specializations of a function or function template
2452 // with a declared return type that uses a placeholder type shall also
2453 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002454 QualType OldDeclaredReturnType =
2455 (Old->getTypeSourceInfo()
2456 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2457 : OldType)->getReturnType();
2458 QualType NewDeclaredReturnType =
2459 (New->getTypeSourceInfo()
2460 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2461 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002462 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002463 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2464 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2465 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002466 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2467 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002468 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2469 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002470 if (New->isCXXClassMember() && New->isOutOfLine())
2471 Diag(New->getLocation(),
2472 diag::err_member_def_does_not_match_ret_type) << New;
2473 else
2474 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Richard Smithbdd14642014-02-04 01:14:30 +00002475 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002476 return true;
2477 }
2478 else
2479 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002480 }
2481
Alp Toker314cc812014-01-25 16:55:45 +00002482 QualType OldReturnType = OldType->getReturnType();
2483 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002484 if (OldReturnType != NewReturnType) {
2485 // If this function has a deduced return type and has already been
2486 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002487 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002488 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002489 New->setType(
2490 SubstAutoType(New->getType(),
2491 OldAT->isDependentType() ? Context.DependentTy
2492 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002493 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002494 SubstAutoType(NewQType,
2495 OldAT->isDependentType() ? Context.DependentTy
2496 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002497 }
2498 }
2499
2500 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2501 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002502 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002503 // Preserve triviality.
2504 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002505
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002506 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002507 // 2 CXXMethodDecls referring to the same function will be injected.
2508 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002509 bool IsClassScopeExplicitSpecialization =
2510 OldMethod->isFunctionTemplateSpecialization() &&
2511 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002512 bool isFriend = NewMethod->getFriendObjectKind();
2513
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002514 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2515 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002516 // -- Member function declarations with the same name and the
2517 // same parameter types cannot be overloaded if any of them
2518 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002519 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002520 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002521 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002522 return true;
2523 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002524
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002525 // C++ [class.mem]p1:
2526 // [...] A member shall not be declared twice in the
2527 // member-specification, except that a nested class or member
2528 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002529 if (ActiveTemplateInstantiations.empty()) {
2530 unsigned NewDiag;
2531 if (isa<CXXConstructorDecl>(OldMethod))
2532 NewDiag = diag::err_constructor_redeclared;
2533 else if (isa<CXXDestructorDecl>(NewMethod))
2534 NewDiag = diag::err_destructor_redeclared;
2535 else if (isa<CXXConversionDecl>(NewMethod))
2536 NewDiag = diag::err_conv_function_redeclared;
2537 else
2538 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002539
Richard Smith57e7ff92012-07-13 04:12:04 +00002540 Diag(New->getLocation(), NewDiag);
2541 } else {
2542 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2543 << New << New->getType();
2544 }
Richard Smithbdd14642014-02-04 01:14:30 +00002545 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002546
2547 // Complain if this is an explicit declaration of a special
2548 // member that was initially declared implicitly.
2549 //
2550 // As an exception, it's okay to befriend such methods in order
2551 // to permit the implicit constructor/destructor/operator calls.
2552 } else if (OldMethod->isImplicit()) {
2553 if (isFriend) {
2554 NewMethod->setImplicit();
2555 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002556 Diag(NewMethod->getLocation(),
2557 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002558 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002559 return true;
2560 }
Richard Smith337a5a12012-06-08 01:30:54 +00002561 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002562 Diag(NewMethod->getLocation(),
2563 diag::err_definition_of_explicitly_defaulted_member)
2564 << getSpecialMember(OldMethod);
2565 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002566 }
2567 }
2568
Richard Smith10876ef2013-01-17 01:30:42 +00002569 // C++11 [dcl.attr.noreturn]p1:
2570 // The first declaration of a function shall specify the noreturn
2571 // attribute if any declaration of that function specifies the noreturn
2572 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002573 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2574 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2575 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002576 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002577 diag::note_noreturn_missing_first_decl);
2578 }
2579
Richard Smithe233fbf2013-01-28 22:42:45 +00002580 // C++11 [dcl.attr.depend]p2:
2581 // The first declaration of a function shall specify the
2582 // carries_dependency attribute for its declarator-id if any declaration
2583 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002584 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2585 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2586 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002587 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002588 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002589 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2590 }
2591
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002592 // (C++98 8.3.5p3):
2593 // All declarations for a function shall agree exactly in both the
2594 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002595 // We also want to respect all the extended bits except noreturn.
2596
2597 // noreturn should now match unless the old type info didn't have it.
2598 QualType OldQTypeForComparison = OldQType;
2599 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2600 assert(OldQType == QualType(OldType, 0));
2601 const FunctionType *OldTypeForComparison
2602 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2603 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2604 assert(OldQTypeForComparison.isCanonical());
2605 }
2606
Rafael Espindolaf4187652013-02-14 01:18:37 +00002607 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002608 // As a special case, retain the language linkage from previous
2609 // declarations of a friend function as an extension.
2610 //
2611 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2612 // and is useful because there's otherwise no way to specify language
2613 // linkage within class scope.
2614 //
2615 // Check cautiously as the friend object kind isn't yet complete.
2616 if (New->getFriendObjectKind() != Decl::FOK_None) {
2617 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002618 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002619 } else {
2620 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002621 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002622 return true;
2623 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002624 }
2625
John McCall4f5019e2010-12-19 02:44:49 +00002626 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002627 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002628
Richard Smith541b38b2013-09-20 01:15:31 +00002629 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2630 New->isLocalExternDecl()) {
2631 // It's OK if we couldn't merge types for a local function declaraton
2632 // if either the old or new type is dependent. We'll merge the types
2633 // when we instantiate the function.
2634 return false;
2635 }
2636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002637 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002638 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002639
2640 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002641 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002642 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002643 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002644 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2645 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002646 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002647 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002648 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002649 // The old declaration provided a function prototype, but the
2650 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002651 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002652 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
Alp Toker314cc812014-01-25 16:55:45 +00002653 NewQType =
2654 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2655 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002656 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002657 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002658
2659 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002660 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002661 for (const auto &ParamType : OldProto->param_types()) {
2662 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2663 SourceLocation(), 0, ParamType,
2664 /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002665 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002666 Param->setImplicit();
2667 Params.push_back(Param);
2668 }
2669
David Blaikie9c70e042011-09-21 18:16:56 +00002670 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002671 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002672
Richard Smith1c34fb72013-08-13 18:18:50 +00002673 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002674 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002675
Douglas Gregora74a2972009-03-06 22:43:54 +00002676 // GNU C permits a K&R definition to follow a prototype declaration
2677 // if the declared types of the parameters in the K&R definition
2678 // match the types in the prototype declaration, even when the
2679 // promoted types of the parameters from the K&R definition differ
2680 // from the types in the prototype. GCC then keeps the types from
2681 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002682 //
2683 // If a variadic prototype is followed by a non-variadic K&R definition,
2684 // the K&R definition becomes variadic. This is sort of an edge case, but
2685 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2686 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002687 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002688 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002689 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002690 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002691 SmallVector<QualType, 16> ArgTypes;
2692 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002693 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002694 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002695 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002696 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregora74a2972009-03-06 22:43:54 +00002698 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002699 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2700 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002701 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002702 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002703 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002704 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2705 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002706 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002707 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002708 ArgTypes.push_back(NewParm->getType());
2709 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002710 NewParm->getType(),
2711 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002712 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2713 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002714 Warnings.push_back(Warn);
2715 ArgTypes.push_back(NewParm->getType());
2716 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002717 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002718 }
2719
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002720 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002721 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2722 Diag(Warnings[Warn].NewParm->getLocation(),
2723 diag::ext_param_promoted_not_compatible_with_prototype)
2724 << Warnings[Warn].PromotedType
2725 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002726 if (Warnings[Warn].OldParm->getLocation().isValid())
2727 Diag(Warnings[Warn].OldParm->getLocation(),
2728 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002729 }
2730
Richard Smith1c34fb72013-08-13 18:18:50 +00002731 if (MergeTypeWithOld)
2732 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2733 OldProto->getExtProtoInfo()));
2734 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002735 }
2736
2737 // Fall through to diagnose conflicting types.
2738 }
2739
John McCallad327cd2013-04-14 08:50:55 +00002740 // A function that has already been declared has been redeclared or
2741 // defined with a different type; show an appropriate diagnostic.
2742
2743 // If the previous declaration was an implicitly-generated builtin
2744 // declaration, then at the very least we should use a specialized note.
2745 unsigned BuiltinID;
2746 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2747 // If it's actually a library-defined builtin function like 'malloc'
2748 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002749 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002750 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002751 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002752 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002753
2754 // If this is a global redeclaration, just forget hereafter
2755 // about the "builtin-ness" of the function.
2756 //
2757 // Doing this for local extern declarations is problematic. If
2758 // the builtin declaration remains visible, a second invalid
2759 // local declaration will produce a hard error; if it doesn't
2760 // remain visible, a single bogus local redeclaration (which is
2761 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002762 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002763 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2764
Douglas Gregor893c2c92009-03-23 17:47:24 +00002765 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002766 }
Steve Naroff17832a42008-01-16 15:01:34 +00002767
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002768 PrevDiag = diag::note_previous_builtin_declaration;
2769 }
2770
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002771 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002772 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002773 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002774}
2775
Douglas Gregore62c0a42009-02-24 01:23:02 +00002776/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002777/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002778///
2779/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002780/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002781/// the new declaration, once we know that New is in fact a
2782/// redeclaration of Old.
2783///
2784/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002785bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002786 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002787 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002788 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002789
Douglas Gregore62c0a42009-02-24 01:23:02 +00002790 // Merge "pure" flag.
2791 if (Old->isPure())
2792 New->setPure();
2793
Rafael Espindolabefe1302012-11-25 14:07:59 +00002794 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002795 if (Old->getMostRecentDecl()->isUsed(false))
2796 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002797
John McCallf79e87d2011-03-02 04:00:57 +00002798 // Merge attributes from the parameters. These can mismatch with K&R
2799 // declarations.
2800 if (New->getNumParams() == Old->getNumParams())
2801 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2802 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002803 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002804
David Blaikiebbafb8a2012-03-11 07:00:24 +00002805 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002806 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002807
Rafael Espindola8778c282012-11-29 16:09:03 +00002808 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002809 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2810 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002811 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002812 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002813 New->setType(Merged);
2814
Douglas Gregore62c0a42009-02-24 01:23:02 +00002815 return false;
2816}
2817
John McCall31168b02011-06-15 23:02:42 +00002818
John McCallf79e87d2011-03-02 04:00:57 +00002819void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002820 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002821
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002822 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002823 AvailabilityMergeKind MergeKind =
2824 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2825 : AMK_Override;
2826 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002827
2828 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002829 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2830 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002831 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002832 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002833 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002834 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002835
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002836 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002837}
2838
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002839/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2840/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002841/// emitting diagnostics as appropriate.
2842///
2843/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002844/// to here in AddInitializerToDecl. We can't check them before the initializer
2845/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002846void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2847 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002848 if (New->isInvalidDecl() || Old->isInvalidDecl())
2849 return;
2850
2851 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002852 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002853 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002854 // We don't know what the new type is until the initializer is attached.
2855 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002856 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2857 // These could still be something that needs exception specs checked.
2858 return MergeVarDeclExceptionSpecs(New, Old);
2859 }
Richard Smith30482bc2011-02-20 03:19:35 +00002860 // C++ [basic.link]p10:
2861 // [...] the types specified by all declarations referring to a given
2862 // object or function shall be identical, except that declarations for an
2863 // array object can specify array types that differ by the presence or
2864 // absence of a major array bound (8.3.4).
2865 else if (Old->getType()->isIncompleteArrayType() &&
2866 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002867 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2868 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2869 if (Context.hasSameType(OldArray->getElementType(),
2870 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002871 MergedT = New->getType();
2872 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002873 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002874 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2875 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2876 if (Context.hasSameType(OldArray->getElementType(),
2877 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002878 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002879 } else if (New->getType()->isObjCObjectPointerType() &&
2880 Old->getType()->isObjCObjectPointerType()) {
2881 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2882 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002883 }
2884 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002885 // C 6.2.7p2:
2886 // All declarations that refer to the same object or function shall have
2887 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002888 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2889 }
2890 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002891 // It's OK if we couldn't merge types if either type is dependent, for a
2892 // block-scope variable. In other cases (static data members of class
2893 // templates, variable templates, ...), we require the types to be
2894 // equivalent.
2895 // FIXME: The C++ standard doesn't say anything about this.
2896 if ((New->getType()->isDependentType() ||
2897 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2898 // If the old type was dependent, we can't merge with it, so the new type
2899 // becomes dependent for now. We'll reproduce the original type when we
2900 // instantiate the TypeSourceInfo for the variable.
2901 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2902 New->setType(Context.DependentTy);
2903 return;
2904 }
2905
2906 // FIXME: Even if this merging succeeds, some other non-visible declaration
2907 // of this variable might have an incompatible type. For instance:
2908 //
2909 // extern int arr[];
2910 // void f() { extern int arr[2]; }
2911 // void g() { extern int arr[3]; }
2912 //
2913 // Neither C nor C++ requires a diagnostic for this, but we should still try
2914 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002915 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002916 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002917 Diag(Old->getLocation(), diag::note_previous_definition);
2918 return New->setInvalidDecl();
2919 }
John McCallb65e8fe2013-04-01 18:34:28 +00002920
2921 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002922 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002923 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002924 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002925}
2926
Richard Smith3c785782013-09-03 21:00:58 +00002927static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2928 LookupResult &Previous) {
2929 // C11 6.2.7p4:
2930 // For an identifier with internal or external linkage declared
2931 // in a scope in which a prior declaration of that identifier is
2932 // visible, if the prior declaration specifies internal or
2933 // external linkage, the type of the identifier at the later
2934 // declaration becomes the composite type.
2935 //
2936 // If the variable isn't visible, we do not merge with its type.
2937 if (Previous.isShadowed())
2938 return false;
2939
2940 if (S.getLangOpts().CPlusPlus) {
2941 // C++11 [dcl.array]p3:
2942 // If there is a preceding declaration of the entity in the same
2943 // scope in which the bound was specified, an omitted array bound
2944 // is taken to be the same as in that earlier declaration.
2945 return NewVD->isPreviousDeclInSameBlockScope() ||
2946 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2947 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2948 } else {
2949 // If the old declaration was function-local, don't merge with its
2950 // type unless we're in the same function.
2951 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2952 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2953 }
2954}
2955
Chris Lattner01564d92007-01-27 19:27:06 +00002956/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2957/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2958/// situation, merging decls or emitting diagnostics as appropriate.
2959///
Mike Stump11289f42009-09-09 15:08:12 +00002960/// Tentative definition rules (C99 6.9.2p2) are checked by
2961/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002962/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002963///
Richard Smith3c785782013-09-03 21:00:58 +00002964void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002965 // If the new decl is already invalid, don't do any other checking.
2966 if (New->isInvalidDecl())
2967 return;
Mike Stump11289f42009-09-09 15:08:12 +00002968
Richard Smithbeef3452014-01-16 23:39:20 +00002969 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2970
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002971 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002972 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002973 VarTemplateDecl *OldTemplate = 0;
2974 if (Previous.isSingleResult()) {
2975 if (NewTemplate) {
2976 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2977 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2978 } else
2979 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002980 }
2981 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002982 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002983 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002984 Diag(Previous.getRepresentativeDecl()->getLocation(),
2985 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002986 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002987 }
Chris Lattner84966392008-03-03 03:28:21 +00002988
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00002989 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2990 return;
2991
Richard Smithbeef3452014-01-16 23:39:20 +00002992 // Ensure the template parameters are compatible.
2993 if (NewTemplate &&
2994 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
2995 OldTemplate->getTemplateParameters(),
2996 /*Complain=*/true, TPL_TemplateMatch))
2997 return;
2998
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002999 // C++ [class.mem]p1:
3000 // A member shall not be declared twice in the member-specification [...]
3001 //
3002 // Here, we need only consider static data members.
3003 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3004 Diag(New->getLocation(), diag::err_duplicate_member)
3005 << New->getIdentifier();
3006 Diag(Old->getLocation(), diag::note_previous_declaration);
3007 New->setInvalidDecl();
3008 }
3009
Douglas Gregor32c17572012-01-01 20:30:41 +00003010 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003011 // Warn if an already-declared variable is made a weak_import in a subsequent
3012 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003013 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003014 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003015 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003016 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3017 Diag(Old->getLocation(), diag::note_previous_definition);
3018 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003019 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003020 }
Chris Lattner84966392008-03-03 03:28:21 +00003021
Richard Smith30482bc2011-02-20 03:19:35 +00003022 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003023 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3024
Richard Smith30482bc2011-02-20 03:19:35 +00003025 if (New->isInvalidDecl())
3026 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003027
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003028 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003029 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003030 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003031 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003032 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003033 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003034 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003037 // For an identifier declared with the storage-class specifier
3038 // extern in a scope in which a prior declaration of that
3039 // identifier is visible,23) if the prior declaration specifies
3040 // internal or external linkage, the linkage of the identifier at
3041 // the later declaration is the same as the linkage specified at
3042 // the prior declaration. If no prior declaration is visible, or
3043 // if the prior declaration specifies no linkage, then the
3044 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003045 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003046 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003047 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003048 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003049 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003050 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003051 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003052 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003053 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003054
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003055 // Check if extern is followed by non-extern and vice-versa.
3056 if (New->hasExternalStorage() &&
3057 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3058 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3059 Diag(Old->getLocation(), diag::note_previous_definition);
3060 return New->setInvalidDecl();
3061 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003062 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3063 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003064 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3065 Diag(Old->getLocation(), diag::note_previous_definition);
3066 return New->setInvalidDecl();
3067 }
3068
Steve Naroffa5629372008-09-17 14:05:40 +00003069 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003070
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003071 // FIXME: The test for external storage here seems wrong? We still
3072 // need to check for mismatches.
3073 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003074 // Don't complain about out-of-line definitions of static members.
3075 !(Old->getLexicalDeclContext()->isRecord() &&
3076 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003077 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003078 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003079 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003080 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003081
Richard Smithfd3834f2013-04-13 02:43:54 +00003082 if (New->getTLSKind() != Old->getTLSKind()) {
3083 if (!Old->getTLSKind()) {
3084 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3085 Diag(Old->getLocation(), diag::note_previous_declaration);
3086 } else if (!New->getTLSKind()) {
3087 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3088 Diag(Old->getLocation(), diag::note_previous_declaration);
3089 } else {
3090 // Do not allow redeclaration to change the variable between requiring
3091 // static and dynamic initialization.
3092 // FIXME: GCC allows this, but uses the TLS keyword on the first
3093 // declaration to determine the kind. Do we need to be compatible here?
3094 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3095 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3096 Diag(Old->getLocation(), diag::note_previous_declaration);
3097 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003098 }
3099
Sebastian Redlf1842912010-02-02 18:35:11 +00003100 // C++ doesn't have tentative definitions, so go right ahead and check here.
3101 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003102 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003103 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003104 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003105 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003106 Diag(Def->getLocation(), diag::note_previous_definition);
3107 New->setInvalidDecl();
3108 return;
3109 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003110
Rafael Espindolaf4187652013-02-14 01:18:37 +00003111 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003112 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3113 Diag(Old->getLocation(), diag::note_previous_definition);
3114 New->setInvalidDecl();
3115 return;
3116 }
3117
Rafael Espindolabefe1302012-11-25 14:07:59 +00003118 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003119 if (Old->getMostRecentDecl()->isUsed(false))
3120 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003121
Douglas Gregor0760fa12009-03-10 23:43:53 +00003122 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003123 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003124 if (NewTemplate)
3125 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003126
3127 // Inherit access appropriately.
3128 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003129 if (NewTemplate)
3130 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003131}
3132
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003133/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3134/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003135Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003136 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003137 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003138}
3139
David Majnemer2206bf52014-03-05 08:57:59 +00003140static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003141 if (!S.Context.getLangOpts().CPlusPlus)
3142 return;
3143
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003144 if (isa<CXXRecordDecl>(Tag->getParent())) {
3145 // If this tag is the direct child of a class, number it if
3146 // it is anonymous.
3147 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3148 return;
3149 MangleNumberingContext &MCtx =
3150 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003151 S.Context.setManglingNumber(
3152 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003153 return;
3154 }
3155
3156 // If this tag isn't a direct child of a class, number it if it is local.
3157 Decl *ManglingContextDecl;
3158 if (MangleNumberingContext *MCtx =
3159 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3160 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003161 S.Context.setManglingNumber(
3162 Tag,
3163 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003164 }
3165}
3166
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003167/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003168/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003169/// parameters to cope with template friend declarations.
3170Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3171 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003172 MultiTemplateParamsArg TemplateParams,
3173 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003174 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003175 TagDecl *Tag = 0;
3176 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3177 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003178 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003179 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003180 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003181 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003182
3183 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003184 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003185
John McCall07e91c02009-08-06 02:15:43 +00003186 // Note that the above type specs guarantee that the
3187 // type rep is a Decl, whereas in many of the others
3188 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003189 if (isa<TagDecl>(TagD))
3190 Tag = cast<TagDecl>(TagD);
3191 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3192 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003193 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003194
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003195 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003196 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003197 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003198 if (Tag->isInvalidDecl())
3199 return Tag;
3200 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003201
Nuno Lopese9823fa2009-12-17 11:35:26 +00003202 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3203 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3204 // or incomplete types shall not be restrict-qualified."
3205 if (TypeQuals & DeclSpec::TQ_restrict)
3206 Diag(DS.getRestrictSpecLoc(),
3207 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3208 << DS.getSourceRange();
3209 }
3210
Richard Smitha77a0a62011-08-15 21:04:07 +00003211 if (DS.isConstexprSpecified()) {
3212 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3213 // and definitions of functions and variables.
3214 if (Tag)
3215 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3216 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3217 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003218 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3219 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003220 else
3221 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3222 // Don't emit warnings after this error.
3223 return TagD;
3224 }
3225
Richard Smithb1402ae2013-03-18 22:52:47 +00003226 DiagnoseFunctionSpecifiers(DS);
3227
Douglas Gregor3dad8422009-09-26 06:47:28 +00003228 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003229 // If we're dealing with a decl but not a TagDecl, assume that
3230 // whatever routines created it handled the friendship aspect.
3231 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003232 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003233 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003234 }
John McCallaa017372011-03-22 23:00:04 +00003235
Richard Smithb1402ae2013-03-18 22:52:47 +00003236 CXXScopeSpec &SS = DS.getTypeSpecScope();
3237 bool IsExplicitSpecialization =
3238 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3239 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3240 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3241 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3242 // nested-name-specifier unless it is an explicit instantiation
3243 // or an explicit specialization.
3244 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3245 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3246 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3247 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3248 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3249 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3250 << SS.getRange();
3251 return 0;
3252 }
3253
3254 // Track whether this decl-specifier declares anything.
3255 bool DeclaresAnything = true;
3256
3257 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003258 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003259 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003260 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003261 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003262 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003263 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003264
Richard Smithb1402ae2013-03-18 22:52:47 +00003265 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003266 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003267 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003268
Richard Smithb1402ae2013-03-18 22:52:47 +00003269 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003270 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003271 CurContext->isRecord() &&
3272 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3273 // Handle 2 kinds of anonymous struct:
3274 // struct STRUCT;
3275 // and
3276 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3277 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003278 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003279 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3280 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003281 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003282 << DS.getSourceRange();
3283 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3284 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003285 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003286
3287 // Skip all the checks below if we have a type error.
3288 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3289 (TagD && TagD->isInvalidDecl()))
3290 return TagD;
3291
3292 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003293 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3294 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3295 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003296 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3297 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003298
John McCallaa017372011-03-22 23:00:04 +00003299 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003300 // Customize diagnostic for a typedef missing a name.
3301 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003302 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003303 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003304 else
3305 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003306 }
Mike Stump11289f42009-09-09 15:08:12 +00003307
Richard Smithb1402ae2013-03-18 22:52:47 +00003308 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003309 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3310 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3311 << Tag->getTagKind()
3312 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3313
Richard Smithb1402ae2013-03-18 22:52:47 +00003314 ActOnDocumentableDecl(TagD);
3315
3316 // C 6.7/2:
3317 // A declaration [...] shall declare at least a declarator [...], a tag,
3318 // or the members of an enumeration.
3319 // C++ [dcl.dcl]p3:
3320 // [If there are no declarators], and except for the declaration of an
3321 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3322 // names into the program, or shall redeclare a name introduced by a
3323 // previous declaration.
3324 if (!DeclaresAnything) {
3325 // In C, we allow this as a (popular) extension / bug. Don't bother
3326 // producing further diagnostics for redundant qualifiers after this.
3327 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3328 return TagD;
3329 }
3330
3331 // C++ [dcl.stc]p1:
3332 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3333 // init-declarator-list of the declaration shall not be empty.
3334 // C++ [dcl.fct.spec]p1:
3335 // If a cv-qualifier appears in a decl-specifier-seq, the
3336 // init-declarator-list of the declaration shall not be empty.
3337 //
3338 // Spurious qualifiers here appear to be valid in C.
3339 unsigned DiagID = diag::warn_standalone_specifier;
3340 if (getLangOpts().CPlusPlus)
3341 DiagID = diag::ext_standalone_specifier;
3342
3343 // Note that a linkage-specification sets a storage class, but
3344 // 'extern "C" struct foo;' is actually valid and not theoretically
3345 // useless.
3346 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3347 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3348 Diag(DS.getStorageClassSpecLoc(), DiagID)
3349 << DeclSpec::getSpecifierName(SCS);
3350
Richard Smithb4a9e862013-04-12 22:46:28 +00003351 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3352 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3353 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003354 if (DS.getTypeQualifiers()) {
3355 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3356 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3357 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3358 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3359 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003360 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3361 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003362 }
3363
Eli Friedmane3217952011-12-17 00:36:09 +00003364 // Warn about ignored type attributes, for example:
3365 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003366 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003367 if (!DS.getAttributes().empty()) {
3368 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3369 if (TypeSpecType == DeclSpec::TST_class ||
3370 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003371 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003372 TypeSpecType == DeclSpec::TST_union ||
3373 TypeSpecType == DeclSpec::TST_enum) {
3374 AttributeList* attrs = DS.getAttributes().getList();
3375 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003376 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003377 << attrs->getName()
3378 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3379 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003380 TypeSpecType == DeclSpec::TST_union ? 2 :
3381 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003382 attrs = attrs->getNext();
3383 }
3384 }
3385 }
John McCallaa017372011-03-22 23:00:04 +00003386
John McCall48871652010-08-21 09:40:31 +00003387 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003388}
3389
John McCallea305ed2009-12-18 10:40:03 +00003390/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003391/// check if there's an existing declaration that can't be overloaded.
3392///
3393/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003394static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3395 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003396 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003397 DeclarationName Name,
3398 SourceLocation NameLoc,
3399 unsigned diagnostic) {
3400 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3401 Sema::ForRedeclaration);
3402 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003403
John McCallea305ed2009-12-18 10:40:03 +00003404 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003405 return false;
3406
3407 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003408 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003409 assert(PrevDecl && "Expected a non-null Decl");
3410
3411 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3412 return false;
John McCall1f82f242009-11-18 22:49:29 +00003413
John McCallea305ed2009-12-18 10:40:03 +00003414 SemaRef.Diag(NameLoc, diagnostic) << Name;
3415 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003416
3417 return true;
3418}
3419
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003420/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3421/// anonymous struct or union AnonRecord into the owning context Owner
3422/// and scope S. This routine will be invoked just after we realize
3423/// that an unnamed union or struct is actually an anonymous union or
3424/// struct, e.g.,
3425///
3426/// @code
3427/// union {
3428/// int i;
3429/// float f;
3430/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3431/// // f into the surrounding scope.x
3432/// @endcode
3433///
3434/// This routine is recursive, injecting the names of nested anonymous
3435/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003436static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003437 DeclContext *Owner,
3438 RecordDecl *AnonRecord,
3439 AccessSpecifier AS,
3440 SmallVectorImpl<NamedDecl *> &Chaining,
3441 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003442 unsigned diagKind
3443 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3444 : diag::err_anonymous_struct_member_redecl;
3445
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003446 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003447
3448 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003449 for (auto *D : AnonRecord->decls()) {
3450 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3451 cast<NamedDecl>(D)->getDeclName()) {
3452 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003453 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3454 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003455 // C++ [class.union]p2:
3456 // The names of the members of an anonymous union shall be
3457 // distinct from the names of any other entity in the
3458 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003459 Invalid = true;
3460 } else {
3461 // C++ [class.union]p2:
3462 // For the purpose of name lookup, after the anonymous union
3463 // definition, the members of the anonymous union are
3464 // considered to have been defined in the scope in which the
3465 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003466 unsigned OldChainingSize = Chaining.size();
3467 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003468 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003469 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003470 else
3471 Chaining.push_back(VD);
3472
Francois Pichet783dd6e2010-11-21 06:08:52 +00003473 assert(Chaining.size() >= 2);
3474 NamedDecl **NamedChain =
3475 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3476 for (unsigned i = 0; i < Chaining.size(); i++)
3477 NamedChain[i] = Chaining[i];
3478
3479 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003480 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3481 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003482 NamedChain, Chaining.size());
3483
3484 IndirectField->setAccess(AS);
3485 IndirectField->setImplicit();
3486 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003487
3488 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003489 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003490
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003491 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003492 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003493 }
3494 }
3495
3496 return Invalid;
3497}
3498
Douglas Gregorc4df4072010-04-19 22:54:31 +00003499/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3500/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003501/// illegal input values are mapped to SC_None.
3502static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003503StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3504 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3505 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3506 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003507 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003508 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003509 case DeclSpec::SCS_extern:
3510 if (DS.isExternInLinkageSpec())
3511 return SC_None;
3512 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003513 case DeclSpec::SCS_static: return SC_Static;
3514 case DeclSpec::SCS_auto: return SC_Auto;
3515 case DeclSpec::SCS_register: return SC_Register;
3516 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003517 // Illegal SCSs map to None: error reporting is up to the caller.
3518 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003519 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003520 }
3521 llvm_unreachable("unknown storage class specifier");
3522}
3523
Richard Smithab44d5b2013-12-10 08:25:00 +00003524static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3525 assert(Record->hasInClassInitializer());
3526
Aaron Ballman629afae2014-03-07 19:56:05 +00003527 for (const auto *I : Record->decls()) {
3528 const auto *FD = dyn_cast<FieldDecl>(I);
3529 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003530 FD = IFD->getAnonField();
3531 if (FD && FD->hasInClassInitializer())
3532 return FD->getLocation();
3533 }
3534
3535 llvm_unreachable("couldn't find in-class initializer");
3536}
3537
3538static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3539 SourceLocation DefaultInitLoc) {
3540 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3541 return;
3542
3543 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3544 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3545}
3546
3547static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3548 CXXRecordDecl *AnonUnion) {
3549 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3550 return;
3551
3552 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3553}
3554
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003555/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003556/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003557/// (C++ [class.union]) and a C11 feature; anonymous structures
3558/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003559Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003560 AccessSpecifier AS,
3561 RecordDecl *Record,
3562 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003563 DeclContext *Owner = Record->getDeclContext();
3564
3565 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003566 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003567 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003568 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003569 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003570 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003571 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003572
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003573 // C and C++ require different kinds of checks for anonymous
3574 // structs/unions.
3575 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003577 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003578 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003579 if (Record->isUnion()) {
3580 // C++ [class.union]p6:
3581 // Anonymous unions declared in a named namespace or in the
3582 // global namespace shall be declared static.
3583 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3584 (isa<TranslationUnitDecl>(Owner) ||
3585 (isa<NamespaceDecl>(Owner) &&
3586 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003587 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3588 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003589
3590 // Recover by adding 'static'.
3591 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003592 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003593 }
3594 // C++ [class.union]p6:
3595 // A storage class is not allowed in a declaration of an
3596 // anonymous union in a class scope.
3597 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3598 isa<RecordDecl>(Owner)) {
3599 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003600 diag::err_anonymous_union_with_storage_spec)
3601 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003602
3603 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003604 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3605 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003606 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003607 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003608 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003609
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003610 // Ignore const/volatile/restrict qualifiers.
3611 if (DS.getTypeQualifiers()) {
3612 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3613 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003614 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003615 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3616 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003617 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003618 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003619 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003620 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3621 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003622 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003623 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003624 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003625 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003626 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3627 Diag(DS.getAtomicSpecLoc(),
3628 diag::ext_anonymous_struct_union_qualified)
3629 << Record->isUnion() << "_Atomic"
3630 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003631
3632 DS.ClearTypeQualifiers();
3633 }
3634
Mike Stump11289f42009-09-09 15:08:12 +00003635 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003636 // The member-specification of an anonymous union shall only
3637 // define non-static data members. [Note: nested types and
3638 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003639 for (auto *Mem : Record->decls()) {
3640 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003641 // C++ [class.union]p3:
3642 // An anonymous union shall not have private or protected
3643 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003644 assert(FD->getAccess() != AS_none);
3645 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003646 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3647 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3648 Invalid = true;
3649 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003650
Alexis Hunt97ab5542011-05-16 22:41:40 +00003651 // C++ [class.union]p1
3652 // An object of a class with a non-trivial constructor, a non-trivial
3653 // copy constructor, a non-trivial destructor, or a non-trivial copy
3654 // assignment operator cannot be a member of a union, nor can an
3655 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003656 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003657 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003658 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003659 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003660 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003661 // This is a type that showed up in an
3662 // elaborated-type-specifier inside the anonymous struct or
3663 // union, but which actually declares a type outside of the
3664 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003665 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003666 if (!MemRecord->isAnonymousStructOrUnion() &&
3667 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003668 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003669 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003670 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3671 << (int)Record->isUnion();
3672 else {
3673 // This is a nested type declaration.
3674 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3675 << (int)Record->isUnion();
3676 Invalid = true;
3677 }
Richard Smith254d2662013-01-28 00:54:05 +00003678 } else {
3679 // This is an anonymous type definition within another anonymous type.
3680 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3681 // not part of standard C++.
3682 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003683 diag::ext_anonymous_record_with_anonymous_type)
3684 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003685 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003686 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003687 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003688 } else {
3689 // We have something that isn't a non-static data
3690 // member. Complain about it.
3691 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003692 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003693 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003694 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003695 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003696 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003697 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003698
3699 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003700 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003701 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003702 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003703 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003704 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003705 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003706 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003707 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003708 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003709 }
3710 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003711
3712 // C++11 [class.union]p8 (DR1460):
3713 // At most one variant member of a union may have a
3714 // brace-or-equal-initializer.
3715 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3716 Owner->isRecord())
3717 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3718 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003719 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003720
3721 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003722 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003723 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003724 Invalid = true;
3725 }
3726
John McCallfa2d6922009-10-22 23:31:08 +00003727 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003728 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003729 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003730 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003731
Mike Stump11289f42009-09-09 15:08:12 +00003732 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003733 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003734 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003735 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003736 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003737 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003738 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003739 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003740 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003741 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003742 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003743 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003744 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003745 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003746 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003747 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003748 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003749 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003750 // mutable can only appear on non-static class members, so it's always
3751 // an error here
3752 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3753 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003754 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003755 }
3756
Abramo Bagnaradff19302011-03-08 08:55:46 +00003757 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003758 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003759 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003760 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003761 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003762
3763 // Default-initialize the implicit variable. This initialization will be
3764 // trivial in almost all cases, except if a union member has an in-class
3765 // initializer:
3766 // union { int n = 0; };
3767 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003768 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003769 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003770
Richard Smithab44d5b2013-12-10 08:25:00 +00003771 // Mark this as an anonymous struct/union type.
3772 Record->setAnonymousStructOrUnion(true);
3773
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003774 // Add the anonymous struct/union object to the current
3775 // context. We'll be referencing this object when we refer to one of
3776 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003777 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003778
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003779 // Inject the members of the anonymous struct/union into the owning
3780 // context and into the identifier resolver chain for name lookup
3781 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003782 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003783 Chain.push_back(Anon);
3784
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003785 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3786 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003787 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003788
David Majnemer2206bf52014-03-05 08:57:59 +00003789 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3790 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3791 Decl *ManglingContextDecl;
3792 if (MangleNumberingContext *MCtx =
3793 getCurrentMangleNumberContext(NewVD->getDeclContext(),
3794 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003795 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00003796 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3797 }
3798 }
3799 }
3800
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003801 if (Invalid)
3802 Anon->setInvalidDecl();
3803
John McCall48871652010-08-21 09:40:31 +00003804 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003805}
3806
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003807/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3808/// Microsoft C anonymous structure.
3809/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3810/// Example:
3811///
3812/// struct A { int a; };
3813/// struct B { struct A; int b; };
3814///
3815/// void foo() {
3816/// B var;
3817/// var.a = 3;
3818/// }
3819///
3820Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3821 RecordDecl *Record) {
3822
3823 // If there is no Record, get the record via the typedef.
3824 if (!Record)
3825 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3826
3827 // Mock up a declarator.
3828 Declarator Dc(DS, Declarator::TypeNameContext);
3829 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3830 assert(TInfo && "couldn't build declarator info for anonymous struct");
3831
3832 // Create a declaration for this anonymous struct.
3833 NamedDecl* Anon = FieldDecl::Create(Context,
3834 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003835 DS.getLocStart(),
3836 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003837 /*IdentifierInfo=*/0,
3838 Context.getTypeDeclType(Record),
3839 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003840 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003841 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003842 Anon->setImplicit();
3843
3844 // Add the anonymous struct object to the current context.
3845 CurContext->addDecl(Anon);
3846
3847 // Inject the members of the anonymous struct into the current
3848 // context and into the identifier resolver chain for name lookup
3849 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003850 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003851 Chain.push_back(Anon);
3852
Nico Weberf8bb3de2012-02-01 00:41:00 +00003853 RecordDecl *RecordDef = Record->getDefinition();
3854 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3855 RecordDef, AS_none,
3856 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003857 Anon->setInvalidDecl();
3858
3859 return Anon;
3860}
Steve Naroff2fea1392007-09-02 02:04:30 +00003861
Douglas Gregor92751d42008-11-17 22:58:34 +00003862/// GetNameForDeclarator - Determine the full declaration name for the
3863/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003864DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003865 return GetNameFromUnqualifiedId(D.getName());
3866}
3867
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003868/// \brief Retrieves the declaration name from a parsed unqualified-id.
3869DeclarationNameInfo
3870Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3871 DeclarationNameInfo NameInfo;
3872 NameInfo.setLoc(Name.StartLocation);
3873
Douglas Gregor7861a802009-11-03 01:35:08 +00003874 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003875
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003876 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003877 case UnqualifiedId::IK_Identifier:
3878 NameInfo.setName(Name.Identifier);
3879 NameInfo.setLoc(Name.StartLocation);
3880 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003881
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003882 case UnqualifiedId::IK_OperatorFunctionId:
3883 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3884 Name.OperatorFunctionId.Operator));
3885 NameInfo.setLoc(Name.StartLocation);
3886 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3887 = Name.OperatorFunctionId.SymbolLocations[0];
3888 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3889 = Name.EndLocation.getRawEncoding();
3890 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003891
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003892 case UnqualifiedId::IK_LiteralOperatorId:
3893 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3894 Name.Identifier));
3895 NameInfo.setLoc(Name.StartLocation);
3896 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3897 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003898
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003899 case UnqualifiedId::IK_ConversionFunctionId: {
3900 TypeSourceInfo *TInfo;
3901 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3902 if (Ty.isNull())
3903 return DeclarationNameInfo();
3904 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3905 Context.getCanonicalType(Ty)));
3906 NameInfo.setLoc(Name.StartLocation);
3907 NameInfo.setNamedTypeInfo(TInfo);
3908 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003909 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003910
3911 case UnqualifiedId::IK_ConstructorName: {
3912 TypeSourceInfo *TInfo;
3913 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3914 if (Ty.isNull())
3915 return DeclarationNameInfo();
3916 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3917 Context.getCanonicalType(Ty)));
3918 NameInfo.setLoc(Name.StartLocation);
3919 NameInfo.setNamedTypeInfo(TInfo);
3920 return NameInfo;
3921 }
3922
3923 case UnqualifiedId::IK_ConstructorTemplateId: {
3924 // In well-formed code, we can only have a constructor
3925 // template-id that refers to the current context, so go there
3926 // to find the actual type being constructed.
3927 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3928 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3929 return DeclarationNameInfo();
3930
3931 // Determine the type of the class being constructed.
3932 QualType CurClassType = Context.getTypeDeclType(CurClass);
3933
3934 // FIXME: Check two things: that the template-id names the same type as
3935 // CurClassType, and that the template-id does not occur when the name
3936 // was qualified.
3937
3938 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3939 Context.getCanonicalType(CurClassType)));
3940 NameInfo.setLoc(Name.StartLocation);
3941 // FIXME: should we retrieve TypeSourceInfo?
3942 NameInfo.setNamedTypeInfo(0);
3943 return NameInfo;
3944 }
3945
3946 case UnqualifiedId::IK_DestructorName: {
3947 TypeSourceInfo *TInfo;
3948 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3949 if (Ty.isNull())
3950 return DeclarationNameInfo();
3951 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3952 Context.getCanonicalType(Ty)));
3953 NameInfo.setLoc(Name.StartLocation);
3954 NameInfo.setNamedTypeInfo(TInfo);
3955 return NameInfo;
3956 }
3957
3958 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003959 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003960 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3961 return Context.getNameForTemplate(TName, TNameLoc);
3962 }
3963
3964 } // switch (Name.getKind())
3965
David Blaikie83d382b2011-09-23 05:06:16 +00003966 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003967}
3968
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003969static QualType getCoreType(QualType Ty) {
3970 do {
3971 if (Ty->isPointerType() || Ty->isReferenceType())
3972 Ty = Ty->getPointeeType();
3973 else if (Ty->isArrayType())
3974 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3975 else
3976 return Ty.withoutLocalFastQualifiers();
3977 } while (true);
3978}
3979
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003980/// hasSimilarParameters - Determine whether the C++ functions Declaration
3981/// and Definition have "nearly" matching parameters. This heuristic is
3982/// used to improve diagnostics in the case where an out-of-line function
3983/// definition doesn't match any declaration within the class or namespace.
3984/// Also sets Params to the list of indices to the parameters that differ
3985/// between the declaration and the definition. If hasSimilarParameters
3986/// returns true and Params is empty, then all of the parameters match.
3987static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003988 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003989 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003990 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003991 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003992 if (Declaration->param_size() != Definition->param_size())
3993 return false;
3994 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3995 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3996 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3997
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003998 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003999 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004000 continue;
4001
4002 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4003 QualType DefParamBaseTy = getCoreType(DefParamTy);
4004 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4005 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4006
4007 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4008 (DeclTyName && DeclTyName == DefTyName))
4009 Params.push_back(Idx);
4010 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004011 return false;
4012 }
4013
4014 return true;
4015}
4016
John McCall99b2fe52010-04-29 23:50:39 +00004017/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4018/// declarator needs to be rebuilt in the current instantiation.
4019/// Any bits of declarator which appear before the name are valid for
4020/// consideration here. That's specifically the type in the decl spec
4021/// and the base type in any member-pointer chunks.
4022static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4023 DeclarationName Name) {
4024 // The types we specifically need to rebuild are:
4025 // - typenames, typeofs, and decltypes
4026 // - types which will become injected class names
4027 // Of course, we also need to rebuild any type referencing such a
4028 // type. It's safest to just say "dependent", but we call out a
4029 // few cases here.
4030
4031 DeclSpec &DS = D.getMutableDeclSpec();
4032 switch (DS.getTypeSpecType()) {
4033 case DeclSpec::TST_typename:
4034 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004035 case DeclSpec::TST_underlyingType:
4036 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004037 // Grab the type from the parser.
4038 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004039 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004040 if (T.isNull() || !T->isDependentType()) break;
4041
4042 // Make sure there's a type source info. This isn't really much
4043 // of a waste; most dependent types should have type source info
4044 // attached already.
4045 if (!TSI)
4046 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4047
4048 // Rebuild the type in the current instantiation.
4049 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4050 if (!TSI) return true;
4051
4052 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004053 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4054 DS.UpdateTypeRep(LocType);
4055 break;
4056 }
4057
Richard Smith1620ebd2012-10-01 20:35:07 +00004058 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004059 case DeclSpec::TST_typeofExpr: {
4060 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004061 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004062 if (Result.isInvalid()) return true;
4063 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004064 break;
4065 }
4066
4067 default:
4068 // Nothing to do for these decl specs.
4069 break;
4070 }
4071
4072 // It doesn't matter what order we do this in.
4073 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4074 DeclaratorChunk &Chunk = D.getTypeObject(I);
4075
4076 // The only type information in the declarator which can come
4077 // before the declaration name is the base type of a member
4078 // pointer.
4079 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4080 continue;
4081
4082 // Rebuild the scope specifier in-place.
4083 CXXScopeSpec &SS = Chunk.Mem.Scope();
4084 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4085 return true;
4086 }
4087
4088 return false;
4089}
4090
Anders Carlsson1052fd72011-07-04 16:28:17 +00004091Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004092 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004093 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004094
4095 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004096 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004097 Dcl->setTopLevelDeclInObjCContainer();
4098
4099 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004100}
4101
Richard Smithdda56e42011-04-15 14:24:37 +00004102/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4103/// If T is the name of a class, then each of the following shall have a
4104/// name different from T:
4105/// - every static data member of class T;
4106/// - every member function of class T
4107/// - every member of class T that is itself a type;
4108/// \returns true if the declaration name violates these rules.
4109bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4110 DeclarationNameInfo NameInfo) {
4111 DeclarationName Name = NameInfo.getName();
4112
4113 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4114 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4115 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4116 return true;
4117 }
4118
4119 return false;
4120}
Douglas Gregor31feb332012-03-17 23:06:31 +00004121
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004122/// \brief Diagnose a declaration whose declarator-id has the given
4123/// nested-name-specifier.
4124///
4125/// \param SS The nested-name-specifier of the declarator-id.
4126///
4127/// \param DC The declaration context to which the nested-name-specifier
4128/// resolves.
4129///
4130/// \param Name The name of the entity being declared.
4131///
4132/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004133///
4134/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004135bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004136 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004137 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004138 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004139 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004140 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004141
4142 // If the user provided a superfluous scope specifier that refers back to the
4143 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004144 //
4145 // class X {
4146 // void X::f();
4147 // };
Richard Smitha2302242013-12-05 07:51:02 +00004148 //
4149 // Note, it was once ill-formed to give redundant qualification in all
4150 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004151 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004152 if (Cur->isRecord()) {
4153 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4154 : diag::err_member_extra_qualification)
4155 << Name << FixItHint::CreateRemoval(SS.getRange());
4156 SS.clear();
4157 } else {
4158 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4159 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004160 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004161 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004162
4163 // Check whether the qualifying scope encloses the scope of the original
4164 // declaration.
4165 if (!Cur->Encloses(DC)) {
4166 if (Cur->isRecord())
4167 Diag(Loc, diag::err_member_qualification)
4168 << Name << SS.getRange();
4169 else if (isa<TranslationUnitDecl>(DC))
4170 Diag(Loc, diag::err_invalid_declarator_global_scope)
4171 << Name << SS.getRange();
4172 else if (isa<FunctionDecl>(Cur))
4173 Diag(Loc, diag::err_invalid_declarator_in_function)
4174 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004175 else if (isa<BlockDecl>(Cur))
4176 Diag(Loc, diag::err_invalid_declarator_in_block)
4177 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004178 else
4179 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004180 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004181
Douglas Gregor31feb332012-03-17 23:06:31 +00004182 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004183 }
4184
4185 if (Cur->isRecord()) {
4186 // Cannot qualify members within a class.
4187 Diag(Loc, diag::err_member_qualification)
4188 << Name << SS.getRange();
4189 SS.clear();
4190
4191 // C++ constructors and destructors with incorrect scopes can break
4192 // our AST invariants by having the wrong underlying types. If
4193 // that's the case, then drop this declaration entirely.
4194 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4195 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4196 !Context.hasSameType(Name.getCXXNameType(),
4197 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4198 return true;
4199
4200 return false;
4201 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004202
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004203 // C++11 [dcl.meaning]p1:
4204 // [...] "The nested-name-specifier of the qualified declarator-id shall
4205 // not begin with a decltype-specifer"
4206 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4207 while (SpecLoc.getPrefix())
4208 SpecLoc = SpecLoc.getPrefix();
4209 if (dyn_cast_or_null<DecltypeType>(
4210 SpecLoc.getNestedNameSpecifier()->getAsType()))
4211 Diag(Loc, diag::err_decltype_in_declarator)
4212 << SpecLoc.getTypeLoc().getSourceRange();
4213
Douglas Gregor31feb332012-03-17 23:06:31 +00004214 return false;
4215}
4216
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004217NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4218 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004219 // TODO: consider using NameInfo for diagnostic.
4220 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4221 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004222
Chris Lattner02c04392007-07-25 00:24:17 +00004223 // All of these full declarators require an identifier. If it doesn't have
4224 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004225 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004226 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004227 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004228 diag::err_declarator_need_ident)
4229 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004230 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004231 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4232 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004233
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004234 // The scope passed in may not be a decl scope. Zip up the scope tree until
4235 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004236 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004237 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004238 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004239
John McCall99b2fe52010-04-29 23:50:39 +00004240 DeclContext *DC = CurContext;
4241 if (D.getCXXScopeSpec().isInvalid())
4242 D.setInvalidType();
4243 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004244 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4245 UPPC_DeclarationQualifier))
4246 return 0;
4247
John McCall99b2fe52010-04-29 23:50:39 +00004248 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4249 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004250 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004251 // If we could not compute the declaration context, it's because the
4252 // declaration context is dependent but does not refer to a class,
4253 // class template, or class template partial specialization. Complain
4254 // and return early, to avoid the coming semantic disaster.
4255 Diag(D.getIdentifierLoc(),
4256 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004257 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004258 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004259 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004260 }
John McCall99b2fe52010-04-29 23:50:39 +00004261 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004262
John McCall99b2fe52010-04-29 23:50:39 +00004263 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004264 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004265 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004266
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004267 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4268 Diag(D.getIdentifierLoc(),
4269 diag::err_member_def_undefined_record)
4270 << Name << DC << D.getCXXScopeSpec().getRange();
4271 D.setInvalidType();
4272 } else if (!D.getDeclSpec().isFriendSpecified()) {
4273 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4274 Name, D.getIdentifierLoc())) {
4275 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004276 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004277
4278 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004279 }
John McCall99b2fe52010-04-29 23:50:39 +00004280 }
4281
4282 // Check whether we need to rebuild the type of the given
4283 // declaration in the current instantiation.
4284 if (EnteringContext && IsDependentContext &&
4285 TemplateParamLists.size() != 0) {
4286 ContextRAII SavedContext(*this, DC);
4287 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4288 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004289 }
4290 }
Richard Smithdda56e42011-04-15 14:24:37 +00004291
4292 if (DiagnoseClassNameShadow(DC, NameInfo))
4293 // If this is a typedef, we'll end up spewing multiple diagnostics.
4294 // Just return early; it's safer.
4295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4296 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004297
John McCall8cb7bdf2010-06-04 23:28:52 +00004298 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4299 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004300
Douglas Gregor506bd562010-12-13 22:49:22 +00004301 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4302 UPPC_DeclarationType))
4303 D.setInvalidType();
4304
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004305 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004306 ForRedeclaration);
4307
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004308 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004309 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004310 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004311 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004312
4313 // If the declaration we're planning to build will be a function
4314 // or object with linkage, then look for another declaration with
4315 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004316 //
4317 // If the declaration we're planning to build will be declared with
4318 // external linkage in the translation unit, create any builtin with
4319 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004320 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4321 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004322 else if (CurContext->isFunctionOrMethod() &&
4323 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4324 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004325 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004326 CreateBuiltins =
4327 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4328 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4329 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4330 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004331
4332 if (IsLinkageLookup)
4333 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004334
Richard Smith1c34fb72013-08-13 18:18:50 +00004335 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004336 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004337 LookupQualifiedName(Previous, DC);
4338
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004339 // C++ [dcl.meaning]p1:
4340 // When the declarator-id is qualified, the declaration shall refer to a
4341 // previously declared member of the class or namespace to which the
4342 // qualifier refers (or, in the case of a namespace, of an element of the
4343 // inline namespace set of that namespace (7.3.1)) or to a specialization
4344 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004345 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004346 // Note that we already checked the context above, and that we do not have
4347 // enough information to make sure that Previous contains the declaration
4348 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004349 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004350 // class X {
4351 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004352 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004353 // };
4354 //
Douglas Gregorad590502008-12-15 23:53:10 +00004355 // void X::f(int) { } // ill-formed
4356 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004357 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004358 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004359 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004360
4361 // C++ [dcl.meaning]p1:
4362 // [...] the member shall not merely have been introduced by a
4363 // using-declaration in the scope of the class or namespace nominated by
4364 // the nested-name-specifier of the declarator-id.
4365 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004366 }
4367
John McCall1f82f242009-11-18 22:49:29 +00004368 if (Previous.isSingleResult() &&
4369 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004370 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004371 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004372 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4373 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004374
Douglas Gregor5101c242008-12-05 18:15:24 +00004375 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004376 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004377 }
4378
Douglas Gregor83a586e2008-04-13 21:07:44 +00004379 // In C++, the previous declaration we find might be a tag type
4380 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004381 // tag type. Note that this does does not apply if we're declaring a
4382 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004383 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004384 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004385 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004386
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004387 // Check that there are no default arguments other than in the parameters
4388 // of a function declaration (C++ only).
4389 if (getLangOpts().CPlusPlus)
4390 CheckExtraCXXDefaultArguments(D);
4391
Nico Webercb4c7f42012-12-23 00:40:46 +00004392 NamedDecl *New;
4393
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004394 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004395 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004396 if (TemplateParamLists.size()) {
4397 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004398 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004399 }
Mike Stump11289f42009-09-09 15:08:12 +00004400
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004401 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004402 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004403 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004404 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004405 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004406 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004407 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4408 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004409 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004410
4411 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004412 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004413
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004414 // If this has an identifier and is not an invalid redeclaration or
4415 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004416 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004417 !(D.isRedeclaration() && New->isInvalidDecl())) {
4418 // Only make a locally-scoped extern declaration visible if it is the first
4419 // declaration of this entity. Qualified lookup for such an entity should
4420 // only find this declaration if there is no visible declaration of it.
4421 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4422 PushOnScopeChains(New, S, AddToContext);
4423 if (!AddToContext)
4424 CurContext->addHiddenDecl(New);
4425 }
Mike Stump11289f42009-09-09 15:08:12 +00004426
John McCall48871652010-08-21 09:40:31 +00004427 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004428}
4429
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004430/// Helper method to turn variable array types into constant array
4431/// types in certain situations which would otherwise be errors (for
4432/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004433static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4434 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004435 bool &SizeIsNegative,
4436 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004437 // This method tries to turn a variable array into a constant
4438 // array even when the size isn't an ICE. This is necessary
4439 // for compatibility with code that depends on gcc's buggy
4440 // constant expression folding, like struct {char x[(int)(char*)2];}
4441 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004442 Oversized = 0;
4443
4444 if (T->isDependentType())
4445 return QualType();
4446
John McCall8ccfcb52009-09-24 19:53:00 +00004447 QualifierCollector Qs;
4448 const Type *Ty = Qs.strip(T);
4449
4450 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004451 QualType Pointee = PTy->getPointeeType();
4452 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004453 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4454 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004455 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004456 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004457 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004458 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004459 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4460 QualType Inner = PTy->getInnerType();
4461 QualType FixedType =
4462 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4463 Oversized);
4464 if (FixedType.isNull()) return FixedType;
4465 FixedType = Context.getParenType(FixedType);
4466 return Qs.apply(Context, FixedType);
4467 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004468
4469 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004470 if (!VLATy)
4471 return QualType();
4472 // FIXME: We should probably handle this case
4473 if (VLATy->getElementType()->isVariablyModifiedType())
4474 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004475
Richard Smith42d3af92011-12-07 00:43:50 +00004476 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004477 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004478 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004479 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004480
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004481 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004482 if (Res.isSigned() && Res.isNegative()) {
4483 SizeIsNegative = true;
4484 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004485 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004486
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004487 // Check whether the array is too large to be addressed.
4488 unsigned ActiveSizeBits
4489 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4490 Res);
4491 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4492 Oversized = Res;
4493 return QualType();
4494 }
4495
4496 return Context.getConstantArrayType(VLATy->getElementType(),
4497 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004498}
4499
Abramo Bagnara341ab732012-11-08 14:44:42 +00004500static void
4501FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004502 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4503 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4504 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4505 DstPTL.getPointeeLoc());
4506 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004507 return;
4508 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004509 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4510 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4511 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4512 DstPTL.getInnerLoc());
4513 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4514 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004515 return;
4516 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004517 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4518 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4519 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4520 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004521 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004522 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4523 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4524 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004525}
4526
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004527/// Helper method to turn variable array types into constant array
4528/// types in certain situations which would otherwise be errors (for
4529/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004530static TypeSourceInfo*
4531TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4532 ASTContext &Context,
4533 bool &SizeIsNegative,
4534 llvm::APSInt &Oversized) {
4535 QualType FixedTy
4536 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4537 SizeIsNegative, Oversized);
4538 if (FixedTy.isNull())
4539 return 0;
4540 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4541 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4542 FixedTInfo->getTypeLoc());
4543 return FixedTInfo;
4544}
4545
Richard Smith78165b52013-01-10 23:43:47 +00004546/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004547/// that it can be found later for redeclarations. We include any extern "C"
4548/// declaration that is not visible in the translation unit here, not just
4549/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004550void
Richard Smith39b79682013-06-18 20:15:12 +00004551Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004552 if (!getLangOpts().CPlusPlus &&
4553 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4554 // Don't need to track declarations in the TU in C.
4555 return;
4556
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004557 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004558 // FIXME: There can be multiple such declarations if they are functions marked
4559 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004560 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004561}
4562
Richard Smith39b79682013-06-18 20:15:12 +00004563NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004564 if (ExternalSource) {
4565 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004566 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004567 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004568 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004569 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4570 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004571 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4572 if (Pos == LocallyScopedExternCDecls.end())
4573 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004574 }
4575 }
Richard Smith39b79682013-06-18 20:15:12 +00004576
4577 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004578 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004579}
4580
Eli Friedman574c7452009-04-07 19:37:57 +00004581/// \brief Diagnose function specifiers on a declaration of an identifier that
4582/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004583void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004584 // FIXME: We should probably indicate the identifier in question to avoid
4585 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004586 if (DS.isInlineSpecified())
4587 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004588 diag::err_inline_non_function);
4589
Richard Smithb1402ae2013-03-18 22:52:47 +00004590 if (DS.isVirtualSpecified())
4591 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004592 diag::err_virtual_non_function);
4593
Richard Smithb1402ae2013-03-18 22:52:47 +00004594 if (DS.isExplicitSpecified())
4595 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004596 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004597
Richard Smithb1402ae2013-03-18 22:52:47 +00004598 if (DS.isNoreturnSpecified())
4599 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004600 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004601}
4602
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004603NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004604Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004605 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004606 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4607 if (D.getCXXScopeSpec().isSet()) {
4608 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4609 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004610 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004611 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004612 DC = CurContext;
4613 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004614 }
4615
Richard Smithb1402ae2013-03-18 22:52:47 +00004616 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004617
Richard Smitha77a0a62011-08-15 21:04:07 +00004618 if (D.getDeclSpec().isConstexprSpecified())
4619 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4620 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004621
Douglas Gregord8f446f2010-07-13 06:37:01 +00004622 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4623 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4624 << D.getName().getSourceRange();
4625 return 0;
4626 }
4627
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004628 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004629 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004630
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004631 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004632 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004633
Richard Smith3f1b5d02011-05-05 21:57:07 +00004634 CheckTypedefForVariablyModifiedType(S, NewTD);
4635
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004636 bool Redeclaration = D.isRedeclaration();
4637 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4638 D.setRedeclaration(Redeclaration);
4639 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004640}
4641
Richard Smith3f1b5d02011-05-05 21:57:07 +00004642void
4643Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004644 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4645 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004646 // Note that variably modified types must be fixed before merging the decl so
4647 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004648 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4649 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004650 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004651 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004652
Chris Lattner9fecd742009-04-19 05:21:20 +00004653 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004654 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004655 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004656 TypeSourceInfo *FixedTInfo =
4657 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4658 SizeIsNegative,
4659 Oversized);
4660 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004661 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004662 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004663 } else {
4664 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004665 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004666 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004667 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004668 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004669 Diag(NewTD->getLocation(), diag::err_array_too_large)
4670 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004671 else
Richard Smithdda56e42011-04-15 14:24:37 +00004672 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004673 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004674 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004675 }
4676 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004677}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004678
Richard Smith3f1b5d02011-05-05 21:57:07 +00004679
4680/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4681/// declares a typedef-name, either using the 'typedef' type specifier or via
4682/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4683NamedDecl*
4684Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4685 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004686 // Merge the decl with the existing one if appropriate. If the decl is
4687 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004688 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4689 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004690 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004691 if (!Previous.empty()) {
4692 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004693 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004694 }
4695
Douglas Gregor27821ce2009-07-07 16:35:42 +00004696 // If this is the C FILE type, notify the AST context.
4697 if (IdentifierInfo *II = NewTD->getIdentifier())
4698 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004699 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004700 if (II->isStr("FILE"))
4701 Context.setFILEDecl(NewTD);
4702 else if (II->isStr("jmp_buf"))
4703 Context.setjmp_bufDecl(NewTD);
4704 else if (II->isStr("sigjmp_buf"))
4705 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004706 else if (II->isStr("ucontext_t"))
4707 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004708 }
4709
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004710 return NewTD;
4711}
4712
Douglas Gregor5d68a202009-02-24 19:23:27 +00004713/// \brief Determines whether the given declaration is an out-of-scope
4714/// previous declaration.
4715///
4716/// This routine should be invoked when name lookup has found a
4717/// previous declaration (PrevDecl) that is not in the scope where a
4718/// new declaration by the same name is being introduced. If the new
4719/// declaration occurs in a local scope, previous declarations with
4720/// linkage may still be considered previous declarations (C99
4721/// 6.2.2p4-5, C++ [basic.link]p6).
4722///
4723/// \param PrevDecl the previous declaration found by name
4724/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004725///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004726/// \param DC the context in which the new declaration is being
4727/// declared.
4728///
4729/// \returns true if PrevDecl is an out-of-scope previous declaration
4730/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004731static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004732isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4733 ASTContext &Context) {
4734 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004735 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004736
Douglas Gregoreddf4332009-02-24 20:03:32 +00004737 if (!PrevDecl->hasLinkage())
4738 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004739
David Blaikiebbafb8a2012-03-11 07:00:24 +00004740 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004741 // C++ [basic.link]p6:
4742 // If there is a visible declaration of an entity with linkage
4743 // having the same name and type, ignoring entities declared
4744 // outside the innermost enclosing namespace scope, the block
4745 // scope declaration declares that same entity and receives the
4746 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004747 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004748 if (!OuterContext->isFunctionOrMethod())
4749 // This rule only applies to block-scope declarations.
4750 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004751
4752 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4753 if (PrevOuterContext->isRecord())
4754 // We found a member function: ignore it.
4755 return false;
4756
4757 // Find the innermost enclosing namespace for the new and
4758 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004759 OuterContext = OuterContext->getEnclosingNamespaceContext();
4760 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004761
Douglas Gregorfcee9462010-08-27 22:55:10 +00004762 // The previous declaration is in a different namespace, so it
4763 // isn't the same function.
4764 if (!OuterContext->Equals(PrevOuterContext))
4765 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004766 }
4767
Douglas Gregor5d68a202009-02-24 19:23:27 +00004768 return true;
4769}
4770
John McCall3e11ebe2010-03-15 10:12:16 +00004771static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4772 CXXScopeSpec &SS = D.getCXXScopeSpec();
4773 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004774 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004775}
4776
John McCall31168b02011-06-15 23:02:42 +00004777bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4778 QualType type = decl->getType();
4779 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4780 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4781 // Various kinds of declaration aren't allowed to be __autoreleasing.
4782 unsigned kind = -1U;
4783 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4784 if (var->hasAttr<BlocksAttr>())
4785 kind = 0; // __block
4786 else if (!var->hasLocalStorage())
4787 kind = 1; // global
4788 } else if (isa<ObjCIvarDecl>(decl)) {
4789 kind = 3; // ivar
4790 } else if (isa<FieldDecl>(decl)) {
4791 kind = 2; // field
4792 }
4793
4794 if (kind != -1U) {
4795 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4796 << kind;
4797 }
4798 } else if (lifetime == Qualifiers::OCL_None) {
4799 // Try to infer lifetime.
4800 if (!type->isObjCLifetimeType())
4801 return false;
4802
4803 lifetime = type->getObjCARCImplicitLifetime();
4804 type = Context.getLifetimeQualifiedType(type, lifetime);
4805 decl->setType(type);
4806 }
4807
4808 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4809 // Thread-local variables cannot have lifetime.
4810 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004811 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004812 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004813 << var->getType();
4814 return true;
4815 }
4816 }
4817
4818 return false;
4819}
4820
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004821static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004822 // Ensure that an auto decl is deduced otherwise the checks below might cache
4823 // the wrong linkage.
4824 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4825
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004826 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004827 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004828 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004829 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4830 ND.dropAttr<WeakAttr>();
4831 }
4832 }
4833 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004834 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004835 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4836 ND.dropAttr<WeakRefAttr>();
4837 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004838 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004839
4840 // 'selectany' only applies to externally visible varable declarations.
4841 // It does not apply to functions.
4842 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4843 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4844 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4845 ND.dropAttr<SelectAnyAttr>();
4846 }
4847 }
Nico Rieck8ca0bfc2014-03-31 14:56:58 +00004848
4849 // dll attributes require external linkage.
4850 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
4851 if (!ND.isExternallyVisible()) {
4852 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4853 << &ND << Attr;
4854 ND.setInvalidDecl();
4855 }
4856 }
4857 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
4858 if (!ND.isExternallyVisible()) {
4859 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4860 << &ND << Attr;
4861 ND.setInvalidDecl();
4862 }
4863 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004864}
4865
Nico Rieck82f0b062014-03-31 14:56:15 +00004866static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
4867 NamedDecl *NewDecl,
4868 bool IsSpecialization) {
4869 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
4870 OldDecl = OldTD->getTemplatedDecl();
4871 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
4872 NewDecl = NewTD->getTemplatedDecl();
4873
4874 if (!OldDecl || !NewDecl)
4875 return;
4876
4877 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
4878 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
4879 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
4880 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
4881
4882 // dllimport and dllexport are inheritable attributes so we have to exclude
4883 // inherited attribute instances.
4884 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
4885 (NewExportAttr && !NewExportAttr->isInherited());
4886
4887 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
4888 // the only exception being explicit specializations.
4889 // Implicitly generated declarations are also excluded for now because there
4890 // is no other way to switch these to use dllimport or dllexport.
4891 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
4892 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
4893 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
4894 << NewDecl
4895 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
4896 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4897 NewDecl->setInvalidDecl();
4898 return;
4899 }
4900
4901 // A redeclaration is not allowed to drop a dllimport attribute, the only
4902 // exception being inline function definitions.
4903 // FIXME: Handle inline functions.
4904 // NB: MSVC converts such a declaration to dllexport.
4905 if (OldImportAttr && !HasNewAttr) {
4906 S.Diag(NewDecl->getLocation(),
4907 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4908 << NewDecl << OldImportAttr;
4909 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4910 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
4911 OldDecl->dropAttr<DLLImportAttr>();
4912 NewDecl->dropAttr<DLLImportAttr>();
4913 }
4914}
4915
John McCallc87d9722013-04-02 02:48:58 +00004916/// Given that we are within the definition of the given function,
4917/// will that definition behave like C99's 'inline', where the
4918/// definition is discarded except for optimization purposes?
4919static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4920 // Try to avoid calling GetGVALinkageForFunction.
4921
4922 // All cases of this require the 'inline' keyword.
4923 if (!FD->isInlined()) return false;
4924
4925 // This is only possible in C++ with the gnu_inline attribute.
4926 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4927 return false;
4928
4929 // Okay, go ahead and call the relatively-more-expensive function.
4930
4931#ifndef NDEBUG
4932 // AST quite reasonably asserts that it's working on a function
4933 // definition. We don't really have a way to tell it that we're
4934 // currently defining the function, so just lie to it in +Asserts
4935 // builds. This is an awful hack.
4936 FD->setLazyBody(1);
4937#endif
4938
David Majnemer27d69db2014-04-28 22:17:59 +00004939 bool isC99Inline =
4940 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
John McCallc87d9722013-04-02 02:48:58 +00004941
4942#ifndef NDEBUG
4943 FD->setLazyBody(0);
4944#endif
4945
4946 return isC99Inline;
4947}
4948
Richard Smithac974a32013-06-30 09:48:50 +00004949/// Determine whether a variable is extern "C" prior to attaching
4950/// an initializer. We can't just call isExternC() here, because that
4951/// will also compute and cache whether the declaration is externally
4952/// visible, which might change when we attach the initializer.
4953///
4954/// This can only be used if the declaration is known to not be a
4955/// redeclaration of an internal linkage declaration.
4956///
4957/// For instance:
4958///
4959/// auto x = []{};
4960///
4961/// Attaching the initializer here makes this declaration not externally
4962/// visible, because its type has internal linkage.
4963///
4964/// FIXME: This is a hack.
4965template<typename T>
4966static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4967 if (S.getLangOpts().CPlusPlus) {
4968 // In C++, the overloadable attribute negates the effects of extern "C".
4969 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4970 return false;
4971 }
4972 return D->isExternC();
4973}
4974
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004975static bool shouldConsiderLinkage(const VarDecl *VD) {
4976 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4977 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004978 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004979 if (DC->isFileContext())
4980 return true;
4981 if (DC->isRecord())
4982 return false;
4983 llvm_unreachable("Unexpected context");
4984}
4985
4986static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4987 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4988 if (DC->isFileContext() || DC->isFunctionOrMethod())
4989 return true;
4990 if (DC->isRecord())
4991 return false;
4992 llvm_unreachable("Unexpected context");
4993}
4994
Nico Riecke84f8db2014-03-23 21:24:01 +00004995static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
4996 AttributeList::Kind Kind) {
4997 for (const AttributeList *L = AttrList; L; L = L->getNext())
4998 if (L->getKind() == Kind)
4999 return true;
5000 return false;
5001}
5002
5003static bool hasParsedAttr(Scope *S, const Declarator &PD,
5004 AttributeList::Kind Kind) {
5005 // Check decl attributes on the DeclSpec.
5006 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5007 return true;
5008
5009 // Walk the declarator structure, checking decl attributes that were in a type
5010 // position to the decl itself.
5011 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5012 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5013 return true;
5014 }
5015
5016 // Finally, check attributes on the decl itself.
5017 return hasParsedAttr(S, PD.getAttributes(), Kind);
5018}
5019
Richard Smith541b38b2013-09-20 01:15:31 +00005020/// Adjust the \c DeclContext for a function or variable that might be a
5021/// function-local external declaration.
5022bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5023 if (!DC->isFunctionOrMethod())
5024 return false;
5025
5026 // If this is a local extern function or variable declared within a function
5027 // template, don't add it into the enclosing namespace scope until it is
5028 // instantiated; it might have a dependent type right now.
5029 if (DC->isDependentContext())
5030 return true;
5031
5032 // C++11 [basic.link]p7:
5033 // When a block scope declaration of an entity with linkage is not found to
5034 // refer to some other declaration, then that entity is a member of the
5035 // innermost enclosing namespace.
5036 //
5037 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5038 // semantically-enclosing namespace, not a lexically-enclosing one.
5039 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5040 DC = DC->getParent();
5041 return true;
5042}
5043
Larisse Voufo39a1e502013-08-06 01:03:05 +00005044NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00005045Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005046 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005047 MultiTemplateParamsArg TemplateParamLists,
5048 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005049 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005050 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005051
Douglas Gregorc4df4072010-04-19 22:54:31 +00005052 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00005053 VarDecl::StorageClass SC =
5054 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00005055
Nico Riecke84f8db2014-03-23 21:24:01 +00005056 // dllimport globals without explicit storage class are treated as extern. We
5057 // have to change the storage class this early to get the right DeclContext.
5058 if (SC == SC_None && !DC->isRecord() &&
5059 hasParsedAttr(S, D, AttributeList::AT_DLLImport))
5060 SC = SC_Extern;
5061
Richard Smith541b38b2013-09-20 01:15:31 +00005062 DeclContext *OriginalDC = DC;
5063 bool IsLocalExternDecl = SC == SC_Extern &&
5064 adjustContextForLocalExternDecl(DC);
5065
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005066 if (getLangOpts().OpenCL) {
5067 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5068 QualType NR = R;
5069 while (NR->isPointerType()) {
5070 if (NR->isFunctionPointerType()) {
5071 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5072 D.setInvalidType();
5073 break;
5074 }
5075 NR = NR->getPointeeType();
5076 }
5077
5078 if (!getOpenCLOptions().cl_khr_fp16) {
5079 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5080 // half array type (unless the cl_khr_fp16 extension is enabled).
5081 if (Context.getBaseElementType(R)->isHalfType()) {
5082 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5083 D.setInvalidType();
5084 }
Joey Goulydd7f4562013-01-23 11:56:20 +00005085 }
5086 }
5087
Douglas Gregorc4df4072010-04-19 22:54:31 +00005088 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005089 // mutable can only appear on non-static class members, so it's always
5090 // an error here
5091 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005092 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005093 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005094 }
John McCallc87d9722013-04-02 02:48:58 +00005095
Richard Smithf2c9afc2013-06-17 01:34:01 +00005096 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5097 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5098 D.getDeclSpec().getStorageClassSpecLoc())) {
5099 // In C++11, the 'register' storage class specifier is deprecated.
5100 // Suppress the warning in system macros, it's used in macros in some
5101 // popular C system headers, such as in glibc's htonl() macro.
5102 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5103 diag::warn_deprecated_register)
5104 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5105 }
5106
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005107 IdentifierInfo *II = Name.getAsIdentifierInfo();
5108 if (!II) {
5109 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005110 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005111 return 0;
5112 }
5113
Richard Smithb1402ae2013-03-18 22:52:47 +00005114 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005115
Douglas Gregor212cab32009-03-11 20:22:50 +00005116 if (!DC->isRecord() && S->getFnParent() == 0) {
5117 // C99 6.9p2: The storage-class specifiers auto and register shall not
5118 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005119 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005120 // If this is a register variable with an asm label specified, then this
5121 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005122 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005123 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5124 else
5125 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005126 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005127 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005128 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005129
David Blaikiebbafb8a2012-03-11 07:00:24 +00005130 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005131 // Set up the special work-group-local storage class for variables in the
5132 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005133 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005134 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005135 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005136
Guy Benyei61054192013-02-07 10:55:47 +00005137 // OpenCL v1.2 s6.9.b p4:
5138 // The sampler type cannot be used with the __local and __global address
5139 // space qualifiers.
5140 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5141 R.getAddressSpace() == LangAS::opencl_global)) {
5142 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5143 }
5144
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005145 // OpenCL 1.2 spec, p6.9 r:
5146 // The event type cannot be used to declare a program scope variable.
5147 // The event type cannot be used with the __local, __constant and __global
5148 // address space qualifiers.
5149 if (R->isEventT()) {
5150 if (S->getParent() == 0) {
5151 Diag(D.getLocStart(), diag::err_event_t_global_var);
5152 D.setInvalidType();
5153 }
5154
5155 if (R.getAddressSpace()) {
5156 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5157 D.setInvalidType();
5158 }
5159 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005160 }
5161
Larisse Voufo39a1e502013-08-06 01:03:05 +00005162 bool IsExplicitSpecialization = false;
5163 bool IsVariableTemplateSpecialization = false;
5164 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005165 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005166 VarDecl *NewVD = 0;
5167 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005168 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005169 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005170 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005171 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005172 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005173
5174 if (D.isInvalidType())
5175 NewVD->setInvalidDecl();
5176 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005177 bool Invalid = false;
5178
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005179 if (DC->isRecord() && !CurContext->isRecord()) {
5180 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005181 switch (SC) {
5182 case SC_None:
5183 break;
5184 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005185 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5186 diag::err_static_out_of_line)
5187 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005188 break;
5189 case SC_Auto:
5190 case SC_Register:
5191 case SC_Extern:
5192 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5193 // to names of variables declared in a block or to function parameters.
5194 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5195 // of class members
5196
5197 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5198 diag::err_storage_class_for_static_member)
5199 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5200 break;
5201 case SC_PrivateExtern:
5202 llvm_unreachable("C storage class in c++!");
5203 case SC_OpenCLWorkGroupLocal:
5204 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005205 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005206 }
5207
Richard Smith42973752012-02-16 20:41:22 +00005208 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005209 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5210 if (RD->isLocalClass())
5211 Diag(D.getIdentifierLoc(),
5212 diag::err_static_data_member_not_allowed_in_local_class)
5213 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005214
Richard Smith42973752012-02-16 20:41:22 +00005215 // C++98 [class.union]p1: If a union contains a static data member,
5216 // the program is ill-formed. C++11 drops this restriction.
5217 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005218 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005219 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005220 ? diag::warn_cxx98_compat_static_data_member_in_union
5221 : diag::ext_static_data_member_in_union) << Name;
5222 // We conservatively disallow static data members in anonymous structs.
5223 else if (!RD->getDeclName())
5224 Diag(D.getIdentifierLoc(),
5225 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005226 << Name << RD->isUnion();
5227 }
5228 }
5229
5230 // Match up the template parameter lists with the scope specifier, then
5231 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005232 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5233 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00005234 D.getCXXScopeSpec(),
5235 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5236 ? D.getName().TemplateId
5237 : 0,
5238 TemplateParamLists,
Richard Smithbeef3452014-01-16 23:39:20 +00005239 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005240
Richard Smithbeef3452014-01-16 23:39:20 +00005241 if (TemplateParams) {
5242 if (!TemplateParams->size() &&
5243 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5244 // There is an extraneous 'template<>' for this variable. Complain
5245 // about it, but allow the declaration of the variable.
5246 Diag(TemplateParams->getTemplateLoc(),
5247 diag::err_template_variable_noparams)
5248 << II
5249 << SourceRange(TemplateParams->getTemplateLoc(),
5250 TemplateParams->getRAngleLoc());
5251 TemplateParams = 0;
5252 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005253 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5254 // This is an explicit specialization or a partial specialization.
5255 // FIXME: Check that we can declare a specialization here.
5256 IsVariableTemplateSpecialization = true;
5257 IsPartialSpecialization = TemplateParams->size() > 0;
5258 } else { // if (TemplateParams->size() > 0)
5259 // This is a template declaration.
5260 IsVariableTemplate = true;
5261
5262 // Check that we can declare a template here.
5263 if (CheckTemplateDeclScope(S, TemplateParams))
5264 return 0;
Richard Smith0d963d62014-04-17 02:56:49 +00005265
5266 // Only C++1y supports variable templates (N3651).
5267 Diag(D.getIdentifierLoc(),
5268 getLangOpts().CPlusPlus1y
5269 ? diag::warn_cxx11_compat_variable_template
5270 : diag::ext_variable_template);
Richard Smithbeef3452014-01-16 23:39:20 +00005271 }
5272 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00005273 } else {
5274 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5275 "should have a 'template<>' for this decl");
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277
Larisse Voufo39a1e502013-08-06 01:03:05 +00005278 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005279 SourceLocation TemplateKWLoc =
5280 TemplateParamLists.size() > 0
5281 ? TemplateParamLists[0]->getTemplateLoc()
5282 : SourceLocation();
5283 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005284 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005285 IsPartialSpecialization);
5286 if (Res.isInvalid())
5287 return 0;
5288 NewVD = cast<VarDecl>(Res.get());
5289 AddToScope = false;
5290 } else
5291 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5292 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005293
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005294 // If this is supposed to be a variable template, create it as such.
5295 if (IsVariableTemplate) {
5296 NewTemplate =
5297 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005298 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005299 NewVD->setDescribedVarTemplate(NewTemplate);
5300 }
5301
Richard Smithb2bc2e62011-02-21 20:05:19 +00005302 // If this decl has an auto type in need of deduction, make a note of the
5303 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005304 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005305 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005306
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005307 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005308 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005309 if (NewTemplate)
5310 NewTemplate->setInvalidDecl();
5311 }
Mike Stump11289f42009-09-09 15:08:12 +00005312
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005313 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005314
Richard Smith72db5632014-01-25 21:32:06 +00005315 // If we have any template parameter lists that don't directly belong to
5316 // the variable (matching the scope specifier), store them.
5317 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5318 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005319 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005320 Context, TemplateParamLists.size() - VDTemplateParamLists,
5321 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005322
Richard Smith6331c402012-02-13 22:16:19 +00005323 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005324 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005325 }
5326
Douglas Gregor41866812011-09-12 18:37:38 +00005327 // Set the lexical context. If the declarator has a C++ scope specifier, the
5328 // lexical context will be different from the semantic context.
5329 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005330 if (NewTemplate)
5331 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005332
Richard Smith541b38b2013-09-20 01:15:31 +00005333 if (IsLocalExternDecl)
5334 NewVD->setLocalExternDecl();
5335
Richard Smithb4a9e862013-04-12 22:46:28 +00005336 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005337 if (NewVD->hasLocalStorage()) {
5338 // C++11 [dcl.stc]p4:
5339 // When thread_local is applied to a variable of block scope the
5340 // storage-class-specifier static is implied if it does not appear
5341 // explicitly.
5342 // Core issue: 'static' is not implied if the variable is declared
5343 // 'extern'.
5344 if (SCSpec == DeclSpec::SCS_unspecified &&
5345 TSCS == DeclSpec::TSCS_thread_local &&
5346 DC->isFunctionOrMethod())
5347 NewVD->setTSCSpec(TSCS);
5348 else
5349 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5350 diag::err_thread_non_global)
5351 << DeclSpec::getSpecifierName(TSCS);
5352 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005353 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5354 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005355 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005356 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005357 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005358
John McCallc87d9722013-04-02 02:48:58 +00005359 // C99 6.7.4p3
5360 // An inline definition of a function with external linkage shall
5361 // not contain a definition of a modifiable object with static or
5362 // thread storage duration...
5363 // We only apply this when the function is required to be defined
5364 // elsewhere, i.e. when the function is not 'extern inline'. Note
5365 // that a local variable with thread storage duration still has to
5366 // be marked 'static'. Also note that it's possible to get these
5367 // semantics in C++ using __attribute__((gnu_inline)).
5368 if (SC == SC_Static && S->getFnParent() != 0 &&
5369 !NewVD->getType().isConstQualified()) {
5370 FunctionDecl *CurFD = getCurFunctionDecl();
5371 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5372 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5373 diag::warn_static_local_in_extern_inline);
5374 MaybeSuggestAddingStaticToDecl(CurFD);
5375 }
5376 }
5377
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005378 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005379 if (IsVariableTemplateSpecialization)
5380 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5381 << (IsPartialSpecialization ? 1 : 0)
5382 << FixItHint::CreateRemoval(
5383 D.getDeclSpec().getModulePrivateSpecLoc());
5384 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005385 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5386 << 2
5387 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005388 else if (NewVD->hasLocalStorage())
5389 Diag(NewVD->getLocation(), diag::err_module_private_local)
5390 << 0 << NewVD->getDeclName()
5391 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5392 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005393 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005394 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005395 if (NewTemplate)
5396 NewTemplate->setModulePrivate();
5397 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005398 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005399
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005400 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005401 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005402
Peter Collingbournec6b08572012-08-28 20:37:50 +00005403 if (getLangOpts().CUDA) {
5404 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5405 // storage [duration]."
5406 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005407 (NewVD->hasAttr<CUDASharedAttr>() ||
5408 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005409 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005410 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005411 }
5412
Nico Riecke84f8db2014-03-23 21:24:01 +00005413 // Ensure that dllimport globals without explicit storage class are treated as
5414 // extern. The storage class is set above using parsed attributes. Now we can
5415 // check the VarDecl itself.
5416 assert(!NewVD->hasAttr<DLLImportAttr>() ||
5417 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5418 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5419
John McCall31168b02011-06-15 23:02:42 +00005420 // In auto-retain/release, infer strong retension for variables of
5421 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005422 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005423 NewVD->setInvalidDecl();
5424
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005425 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005426 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005427 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005428 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005429 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005430 if (S->getFnParent() != 0) {
5431 switch (SC) {
5432 case SC_None:
5433 case SC_Auto:
5434 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5435 break;
5436 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005437 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005438 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5439 break;
5440 case SC_Static:
5441 case SC_Extern:
5442 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005443 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005444 break;
5445 }
5446 }
5447
5448 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005449 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005450 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5451 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5452 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5453 if (I != ExtnameUndeclaredIdentifiers.end()) {
5454 NewVD->addAttr(I->second);
5455 ExtnameUndeclaredIdentifiers.erase(I);
5456 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005457 }
5458
John McCalla2a3f7d2010-03-16 21:48:18 +00005459 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005460 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005461 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005462
John McCall1f82f242009-11-18 22:49:29 +00005463 // Don't consider existing declarations that are in a different
5464 // scope and are out-of-semantic-context declarations (if the new
5465 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005466 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5467 D.getCXXScopeSpec().isNotEmpty() ||
5468 IsExplicitSpecialization ||
5469 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005470
Richard Smith1c34fb72013-08-13 18:18:50 +00005471 // Check whether the previous declaration is in the same block scope. This
5472 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5473 if (getLangOpts().CPlusPlus &&
5474 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5475 NewVD->setPreviousDeclInSameBlockScope(
5476 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005477 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005478
David Blaikiebbafb8a2012-03-11 07:00:24 +00005479 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005480 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5481 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005482 // If this is an explicit specialization of a static data member, check it.
5483 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5484 CheckMemberSpecialization(NewVD, Previous))
5485 NewVD->setInvalidDecl();
5486
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005487 // Merge the decl with the existing one if appropriate.
5488 if (!Previous.empty()) {
5489 if (Previous.isSingleResult() &&
5490 isa<FieldDecl>(Previous.getFoundDecl()) &&
5491 D.getCXXScopeSpec().isSet()) {
5492 // The user tried to define a non-static data member
5493 // out-of-line (C++ [dcl.meaning]p1).
5494 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5495 << D.getCXXScopeSpec().getRange();
5496 Previous.clear();
5497 NewVD->setInvalidDecl();
5498 }
5499 } else if (D.getCXXScopeSpec().isSet()) {
5500 // No previous declaration in the qualifying scope.
5501 Diag(D.getIdentifierLoc(), diag::err_no_member)
5502 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005503 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005504 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005505 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005506
Richard Smithbeef3452014-01-16 23:39:20 +00005507 if (!IsVariableTemplateSpecialization)
5508 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005509
Richard Smithbeef3452014-01-16 23:39:20 +00005510 if (NewTemplate) {
5511 VarTemplateDecl *PrevVarTemplate =
5512 NewVD->getPreviousDecl()
5513 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5514 : 0;
5515
5516 // Check the template parameter list of this declaration, possibly
5517 // merging in the template parameter list from the previous variable
5518 // template declaration.
5519 if (CheckTemplateParameterList(
5520 TemplateParams,
5521 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5522 : 0,
5523 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5524 DC->isDependentContext())
5525 ? TPC_ClassTemplateMember
5526 : TPC_VarTemplate))
5527 NewVD->setInvalidDecl();
5528
5529 // If we are providing an explicit specialization of a static variable
5530 // template, make a note of that.
5531 if (PrevVarTemplate &&
5532 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5533 PrevVarTemplate->setMemberSpecialization();
5534 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005535 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005536
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005537 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005538
Richard Smithac974a32013-06-30 09:48:50 +00005539 // If this is the first declaration of an extern C variable, update
5540 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005541 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005542 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005543 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005544
Reid Klecknerd8110b62013-09-10 20:14:30 +00005545 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005546 Decl *ManglingContextDecl;
5547 if (MangleNumberingContext *MCtx =
5548 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5549 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005550 Context.setManglingNumber(
5551 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005552 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005553 }
5554 }
5555
Nico Rieck82f0b062014-03-31 14:56:15 +00005556 if (D.isRedeclaration() && !Previous.empty()) {
5557 checkDLLAttributeRedeclaration(
5558 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5559 IsExplicitSpecialization);
5560 }
5561
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005562 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005563 if (NewVD->isInvalidDecl())
5564 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005565 ActOnDocumentableDecl(NewTemplate);
5566 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005567 }
5568
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005569 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005570}
5571
John McCalldf8b37c2010-03-22 09:20:08 +00005572/// \brief Diagnose variable or built-in function shadowing. Implements
5573/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005574///
John McCalldf8b37c2010-03-22 09:20:08 +00005575/// This method is called whenever a VarDecl is added to a "useful"
5576/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005577///
John McCall2d8c7602010-03-20 04:12:52 +00005578/// \param S the scope in which the shadowing name is being declared
5579/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005580///
John McCalldf8b37c2010-03-22 09:20:08 +00005581void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005582 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005583 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005584 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005585 return;
5586
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005587 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005588 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005589 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005590
5591 DeclContext *NewDC = D->getDeclContext();
5592
John McCall2d8c7602010-03-20 04:12:52 +00005593 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005594 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005595 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005596
John McCalla2a3f7d2010-03-16 21:48:18 +00005597 NamedDecl* ShadowedDecl = R.getFoundDecl();
5598 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5599 return;
5600
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005601 // Fields are not shadowed by variables in C++ static methods.
5602 if (isa<FieldDecl>(ShadowedDecl))
5603 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5604 if (MD->isStatic())
5605 return;
5606
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005607 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5608 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005609 // For shadowing external vars, make sure that we point to the global
5610 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005611 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005612 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005613 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005614 break;
5615 }
5616 }
5617
5618 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5619
John McCall2d8c7602010-03-20 04:12:52 +00005620 // Only warn about certain kinds of shadowing for class members.
5621 if (NewDC && NewDC->isRecord()) {
5622 // In particular, don't warn about shadowing non-class members.
5623 if (!OldDC->isRecord())
5624 return;
5625
5626 // TODO: should we warn about static data members shadowing
5627 // static data members from base classes?
5628
5629 // TODO: don't diagnose for inaccessible shadowed members.
5630 // This is hard to do perfectly because we might friend the
5631 // shadowing context, but that's just a false negative.
5632 }
5633
5634 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005635 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005636 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005637 if (isa<FieldDecl>(ShadowedDecl))
5638 Kind = 3; // field
5639 else
5640 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005641 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005642 Kind = 1; // global
5643 else
5644 Kind = 0; // local
5645
John McCall2d8c7602010-03-20 04:12:52 +00005646 DeclarationName Name = R.getLookupName();
5647
John McCalla2a3f7d2010-03-16 21:48:18 +00005648 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005649 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5650 return;
John McCall2d8c7602010-03-20 04:12:52 +00005651 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005652 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5653}
5654
John McCalldf8b37c2010-03-22 09:20:08 +00005655/// \brief Check -Wshadow without the advantage of a previous lookup.
5656void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005657 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005658 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005659 return;
5660
John McCalldf8b37c2010-03-22 09:20:08 +00005661 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5662 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5663 LookupName(R, S);
5664 CheckShadow(S, D, R);
5665}
5666
Richard Smithac974a32013-06-30 09:48:50 +00005667/// Check for conflict between this global or extern "C" declaration and
5668/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005669template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005670static bool checkGlobalOrExternCConflict(
5671 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5672 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5673 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005674
Richard Smithac974a32013-06-30 09:48:50 +00005675 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5676 // The common case: this global doesn't conflict with any extern "C"
5677 // declaration.
5678 return false;
5679 }
5680
5681 if (Prev) {
5682 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5683 // Both the old and new declarations have C language linkage. This is a
5684 // redeclaration.
5685 Previous.clear();
5686 Previous.addDecl(Prev);
5687 return true;
5688 }
5689
5690 // This is a global, non-extern "C" declaration, and there is a previous
5691 // non-global extern "C" declaration. Diagnose if this is a variable
5692 // declaration.
5693 if (!isa<VarDecl>(ND))
5694 return false;
5695 } else {
5696 // The declaration is extern "C". Check for any declaration in the
5697 // translation unit which might conflict.
5698 if (IsGlobal) {
5699 // We have already performed the lookup into the translation unit.
5700 IsGlobal = false;
5701 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5702 I != E; ++I) {
5703 if (isa<VarDecl>(*I)) {
5704 Prev = *I;
5705 break;
5706 }
5707 }
5708 } else {
5709 DeclContext::lookup_result R =
5710 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5711 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5712 I != E; ++I) {
5713 if (isa<VarDecl>(*I)) {
5714 Prev = *I;
5715 break;
5716 }
5717 // FIXME: If we have any other entity with this name in global scope,
5718 // the declaration is ill-formed, but that is a defect: it breaks the
5719 // 'stat' hack, for instance. Only variables can have mangled name
5720 // clashes with extern "C" declarations, so only they deserve a
5721 // diagnostic.
5722 }
5723 }
5724
5725 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005726 return false;
5727 }
5728
Richard Smithac974a32013-06-30 09:48:50 +00005729 // Use the first declaration's location to ensure we point at something which
5730 // is lexically inside an extern "C" linkage-spec.
5731 assert(Prev && "should have found a previous declaration to diagnose");
5732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005733 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005734 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005735 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005736
5737 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5738 << IsGlobal << ND;
5739 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5740 << IsGlobal;
5741 return false;
5742}
5743
5744/// Apply special rules for handling extern "C" declarations. Returns \c true
5745/// if we have found that this is a redeclaration of some prior entity.
5746///
5747/// Per C++ [dcl.link]p6:
5748/// Two declarations [for a function or variable] with C language linkage
5749/// with the same name that appear in different scopes refer to the same
5750/// [entity]. An entity with C language linkage shall not be declared with
5751/// the same name as an entity in global scope.
5752template<typename T>
5753static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5754 LookupResult &Previous) {
5755 if (!S.getLangOpts().CPlusPlus) {
5756 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005757 // variable declared in function scope. We don't need this in C++, because
5758 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005759 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5760 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5761 Previous.clear();
5762 Previous.addDecl(Prev);
5763 return true;
5764 }
5765 }
5766 return false;
5767 }
5768
5769 // A declaration in the translation unit can conflict with an extern "C"
5770 // declaration.
5771 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5772 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5773
5774 // An extern "C" declaration can conflict with a declaration in the
5775 // translation unit or can be a redeclaration of an extern "C" declaration
5776 // in another scope.
5777 if (isIncompleteDeclExternC(S,ND))
5778 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5779
5780 // Neither global nor extern "C": nothing to do.
5781 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005782}
5783
Richard Smith27d807c2013-04-30 13:56:41 +00005784void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005785 // If the decl is already known invalid, don't check it.
5786 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005787 return;
Mike Stump11289f42009-09-09 15:08:12 +00005788
Abramo Bagnara341ab732012-11-08 14:44:42 +00005789 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5790 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005791
Richard Smith27d807c2013-04-30 13:56:41 +00005792 // Defer checking an 'auto' type until its initializer is attached.
5793 if (T->isUndeducedType())
5794 return;
5795
Richard Smithdc4ccaa2014-03-27 01:22:48 +00005796 if (NewVD->hasAttrs())
5797 CheckAlignasUnderalignment(NewVD);
5798
John McCall8b07ec22010-05-15 11:32:37 +00005799 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005800 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5801 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005802 T = Context.getObjCObjectPointerType(T);
5803 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005804 }
Mike Stump11289f42009-09-09 15:08:12 +00005805
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005806 // Emit an error if an address space was applied to decl with local storage.
5807 // This includes arrays of objects with address space qualifiers, but not
5808 // automatic variables that point to other address spaces.
5809 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005810 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005811 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005812 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005813 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005814 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005815
Tanya Lattner713eef42013-04-05 20:14:50 +00005816 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5817 // __constant address space.
5818 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5819 && T.getAddressSpace() != LangAS::opencl_constant
5820 && !T->isSamplerT()){
5821 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5822 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005823 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005824 }
5825
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005826 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5827 // scope.
5828 if ((getLangOpts().OpenCLVersion >= 120)
5829 && NewVD->isStaticLocal()) {
5830 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5831 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005832 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005833 }
5834
Mike Stumpca5ae662009-04-14 00:57:29 +00005835 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005836 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005837 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005838 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005839 else {
5840 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005841 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005842 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005843 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005844
Chris Lattner9fecd742009-04-19 05:21:20 +00005845 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005846 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005847 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005848 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005849
Chris Lattner9fecd742009-04-19 05:21:20 +00005850 if ((isVM && NewVD->hasLinkage()) ||
5851 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005852 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005853 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005854 TypeSourceInfo *FixedTInfo =
5855 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5856 SizeIsNegative, Oversized);
5857 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005858 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005859 // FIXME: This won't give the correct result for
5860 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005861 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005862
Anders Carlsson6c885802009-02-28 21:56:50 +00005863 if (NewVD->isFileVarDecl())
5864 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005865 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005866 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005867 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005868 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005869 else
5870 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005871 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005872 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005873 return;
Mike Stump11289f42009-09-09 15:08:12 +00005874 }
5875
Abramo Bagnara341ab732012-11-08 14:44:42 +00005876 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005877 if (NewVD->isFileVarDecl())
5878 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5879 else
5880 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005881 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005882 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005883 }
Mike Stump11289f42009-09-09 15:08:12 +00005884
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005885 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005886 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005887 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005888 }
5889
David Majnemer0ffa3312013-05-29 00:56:45 +00005890 if (T->isVoidType()) {
5891 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5892 // of objects and functions.
5893 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5894 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5895 << T;
5896 NewVD->setInvalidDecl();
5897 return;
5898 }
Richard Smith27d807c2013-04-30 13:56:41 +00005899 }
5900
5901 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5902 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5903 NewVD->setInvalidDecl();
5904 return;
5905 }
5906
5907 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5908 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5909 NewVD->setInvalidDecl();
5910 return;
5911 }
5912
5913 if (NewVD->isConstexpr() && !T->isDependentType() &&
5914 RequireLiteralType(NewVD->getLocation(), T,
5915 diag::err_constexpr_var_non_literal)) {
Richard Smith27d807c2013-04-30 13:56:41 +00005916 NewVD->setInvalidDecl();
5917 return;
5918 }
5919}
5920
5921/// \brief Perform semantic checking on a newly-created variable
5922/// declaration.
5923///
5924/// This routine performs all of the type-checking required for a
5925/// variable declaration once it has been built. It is used both to
5926/// check variables after they have been parsed and their declarators
5927/// have been translated into a declaration, and to check variables
5928/// that have been instantiated from a template.
5929///
5930/// Sets NewVD->isInvalidDecl() if an error was encountered.
5931///
5932/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005933bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005934 CheckVariableDeclarationType(NewVD);
5935
5936 // If the decl is already known invalid, don't check it.
5937 if (NewVD->isInvalidDecl())
5938 return false;
5939
John McCallb65e8fe2013-04-01 18:34:28 +00005940 // If we did not find anything by this name, look for a non-visible
5941 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005942 if (Previous.empty() &&
5943 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005944 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005945
Douglas Gregor3552dab2013-01-09 00:47:56 +00005946 // Filter out any non-conflicting previous declarations.
5947 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5948
John McCall1f82f242009-11-18 22:49:29 +00005949 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005950 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005951 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005952 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005953 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005954}
5955
Douglas Gregor36d1b142009-10-06 17:59:45 +00005956/// \brief Data used with FindOverriddenMethod
5957struct FindOverriddenMethodData {
5958 Sema *S;
5959 CXXMethodDecl *Method;
5960};
5961
5962/// \brief Member lookup function that determines whether a given C++
5963/// method overrides a method in a base class, to be used with
5964/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005965static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005966 CXXBasePath &Path,
5967 void *UserData) {
5968 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005969
Douglas Gregor36d1b142009-10-06 17:59:45 +00005970 FindOverriddenMethodData *Data
5971 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005972
5973 DeclarationName Name = Data->Method->getDeclName();
5974
5975 // FIXME: Do we care about other names here too?
5976 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005977 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005978 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5979 CanQualType CT = Data->S->Context.getCanonicalType(T);
5980
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005981 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005982 }
5983
5984 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005985 !Path.Decls.empty();
5986 Path.Decls = Path.Decls.slice(1)) {
5987 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005988 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5989 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005990 return true;
5991 }
5992 }
5993
5994 return false;
5995}
5996
David Blaikie7e414262012-10-17 00:47:58 +00005997namespace {
5998 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5999}
6000/// \brief Report an error regarding overriding, along with any relevant
6001/// overriden methods.
6002///
6003/// \param DiagID the primary error to report.
6004/// \param MD the overriding method.
6005/// \param OEK which overrides to include as notes.
6006static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6007 OverrideErrorKind OEK = OEK_All) {
6008 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6009 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6010 E = MD->end_overridden_methods();
6011 I != E; ++I) {
6012 // This check (& the OEK parameter) could be replaced by a predicate, but
6013 // without lambdas that would be overkill. This is still nicer than writing
6014 // out the diag loop 3 times.
6015 if ((OEK == OEK_All) ||
6016 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6017 (OEK == OEK_Deleted && (*I)->isDeleted()))
6018 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6019 }
6020}
6021
Sebastian Redld5b24532009-11-18 21:51:29 +00006022/// AddOverriddenMethods - See if a method overrides any in the base classes,
6023/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006024bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00006025 // Look for virtual methods in base classes that this method might override.
6026 CXXBasePaths Paths;
6027 FindOverriddenMethodData Data;
6028 Data.Method = MD;
6029 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00006030 bool hasDeletedOverridenMethods = false;
6031 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006032 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00006033 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
Aaron Ballmane6f465e2014-03-14 21:38:48 +00006034 for (auto *I : Paths.found_decls()) {
6035 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00006036 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00006037 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00006038 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00006039 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00006040 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00006041 hasDeletedOverridenMethods |= OldMD->isDeleted();
6042 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006043 AddedAny = true;
6044 }
Sebastian Redld5b24532009-11-18 21:51:29 +00006045 }
6046 }
6047 }
David Blaikie7e414262012-10-17 00:47:58 +00006048
6049 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6050 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6051 }
6052 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6053 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6054 }
6055
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006056 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00006057}
6058
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006059namespace {
6060 // Struct for holding all of the extra arguments needed by
6061 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6062 struct ActOnFDArgs {
6063 Scope *S;
6064 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006065 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006066 bool AddToScope;
6067 };
6068}
6069
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006070namespace {
6071
6072// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006073// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006074class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6075 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006076 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6077 CXXRecordDecl *Parent)
6078 : Context(Context), OriginalFD(TypoFD),
6079 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006080
Craig Toppere14c0f82014-03-12 04:55:44 +00006081 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006082 if (candidate.getEditDistance() == 0)
6083 return false;
6084
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006085 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006086 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6087 CDeclEnd = candidate.end();
6088 CDecl != CDeclEnd; ++CDecl) {
6089 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6090
6091 if (FD && !FD->hasBody() &&
6092 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6093 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6094 CXXRecordDecl *Parent = MD->getParent();
6095 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6096 return true;
6097 } else if (!ExpectedParent) {
6098 return true;
6099 }
6100 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006101 }
6102
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006103 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006104 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006105
6106 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006107 ASTContext &Context;
6108 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006109 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006110};
6111
6112}
6113
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006114/// \brief Generate diagnostics for an invalid function redeclaration.
6115///
6116/// This routine handles generating the diagnostic messages for an invalid
6117/// function redeclaration, including finding possible similar declarations
6118/// or performing typo correction if there are no previous declarations with
6119/// the same name.
6120///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006121/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006122/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006123static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006124 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006125 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006126 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006127 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006128 SmallVector<unsigned, 1> MismatchedParams;
6129 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006130 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006131 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006132 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6133 : diag::err_member_decl_does_not_match;
6134 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6135 IsLocalFriend ? Sema::LookupLocalFriendName
6136 : Sema::LookupOrdinaryName,
6137 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006138
6139 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006140 if (IsLocalFriend)
6141 SemaRef.LookupName(Prev, S);
6142 else
6143 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006144 assert(!Prev.isAmbiguous() &&
6145 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006146 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006147 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6148 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006149 if (!Prev.empty()) {
6150 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6151 Func != FuncEnd; ++Func) {
6152 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006153 if (FD &&
6154 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006155 // Add 1 to the index so that 0 can mean the mismatch didn't
6156 // involve a parameter
6157 unsigned ParamNum =
6158 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6159 NearMatches.push_back(std::make_pair(FD, ParamNum));
6160 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006161 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006162 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006163 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006164 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6165 &ExtraArgs.D.getCXXScopeSpec(), Validator,
John Thompson2255f2c2014-04-23 12:57:01 +00006166 Sema::CTK_ErrorRecovery, IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006167 // Set up everything for the call to ActOnFunctionDeclarator
6168 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6169 ExtraArgs.D.getIdentifierLoc());
6170 Previous.clear();
6171 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006172 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6173 CDeclEnd = Correction.end();
6174 CDecl != CDeclEnd; ++CDecl) {
6175 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006176 if (FD && !FD->hasBody() &&
6177 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006178 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006179 }
6180 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006181 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006182
6183 NamedDecl *Result;
6184 // Retry building the function declaration with the new previous
6185 // declarations, and with errors suppressed.
6186 {
6187 // Trap errors.
6188 Sema::SFINAETrap Trap(SemaRef);
6189
6190 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6191 // pieces need to verify the typo-corrected C++ declaration and hopefully
6192 // eliminate the need for the parameter pack ExtraArgs.
6193 Result = SemaRef.ActOnFunctionDeclarator(
6194 ExtraArgs.S, ExtraArgs.D,
6195 Correction.getCorrectionDecl()->getDeclContext(),
6196 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6197 ExtraArgs.AddToScope);
6198
6199 if (Trap.hasErrorOccurred())
6200 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006201 }
Richard Smithf9b15102013-08-17 00:46:16 +00006202
6203 if (Result) {
6204 // Determine which correction we picked.
6205 Decl *Canonical = Result->getCanonicalDecl();
6206 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6207 I != E; ++I)
6208 if ((*I)->getCanonicalDecl() == Canonical)
6209 Correction.setCorrectionDecl(*I);
6210
6211 SemaRef.diagnoseTypo(
6212 Correction,
6213 SemaRef.PDiag(IsLocalFriend
6214 ? diag::err_no_matching_local_friend_suggest
6215 : diag::err_member_decl_does_not_match_suggest)
6216 << Name << NewDC << IsDefinition);
6217 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006218 }
Richard Smithf9b15102013-08-17 00:46:16 +00006219
6220 // Pretend the typo correction never occurred
6221 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6222 ExtraArgs.D.getIdentifierLoc());
6223 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6224 Previous.clear();
6225 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006226 }
6227
Richard Smithf9b15102013-08-17 00:46:16 +00006228 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6229 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006230
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006231 bool NewFDisConst = false;
6232 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006233 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006234
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006235 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006236 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6237 NearMatch != NearMatchEnd; ++NearMatch) {
6238 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006239 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6240 bool FDisConst = MD && MD->isConst();
6241 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006242
Richard Smith541b38b2013-09-20 01:15:31 +00006243 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006244 if (unsigned Idx = NearMatch->second) {
6245 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006246 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6247 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006248 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6249 : diag::note_local_decl_close_param_match)
6250 << Idx << FDParam->getType()
6251 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006252 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006253 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006254 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006255 } else
Richard Smith114394f2013-08-09 04:35:01 +00006256 SemaRef.Diag(FD->getLocation(),
6257 IsMember ? diag::note_member_def_close_match
6258 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006259 }
Richard Smithf9b15102013-08-17 00:46:16 +00006260 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006261}
6262
David Blaikie30d15442011-10-19 22:56:21 +00006263static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6264 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006265 switch (D.getDeclSpec().getStorageClassSpec()) {
6266 default: llvm_unreachable("Unknown storage class!");
6267 case DeclSpec::SCS_auto:
6268 case DeclSpec::SCS_register:
6269 case DeclSpec::SCS_mutable:
6270 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6271 diag::err_typecheck_sclass_func);
6272 D.setInvalidType();
6273 break;
6274 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006275 case DeclSpec::SCS_extern:
6276 if (D.getDeclSpec().isExternInLinkageSpec())
6277 return SC_None;
6278 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006279 case DeclSpec::SCS_static: {
6280 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6281 // C99 6.7.1p5:
6282 // The declaration of an identifier for a function that has
6283 // block scope shall have no explicit storage-class specifier
6284 // other than extern
6285 // See also (C++ [dcl.stc]p4).
6286 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6287 diag::err_static_block_func);
6288 break;
6289 } else
6290 return SC_Static;
6291 }
6292 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6293 }
6294
6295 // No explicit storage class has already been returned
6296 return SC_None;
6297}
6298
6299static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6300 DeclContext *DC, QualType &R,
6301 TypeSourceInfo *TInfo,
6302 FunctionDecl::StorageClass SC,
6303 bool &IsVirtualOkay) {
6304 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6305 DeclarationName Name = NameInfo.getName();
6306
6307 FunctionDecl *NewFD = 0;
6308 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006309
David Blaikiebbafb8a2012-03-11 07:00:24 +00006310 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006311 // Determine whether the function was written with a
6312 // prototype. This true when:
6313 // - there is a prototype in the declarator, or
6314 // - the type R of the function is some kind of typedef or other reference
6315 // to a type name (which eventually refers to a function type).
6316 bool HasPrototype =
6317 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6318 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6319
David Blaikie30d15442011-10-19 22:56:21 +00006320 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006321 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006322 TInfo, SC, isInline,
6323 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006324 if (D.isInvalidType())
6325 NewFD->setInvalidDecl();
6326
6327 // Set the lexical context.
6328 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6329
6330 return NewFD;
6331 }
6332
6333 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6334 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6335
6336 // Check that the return type is not an abstract class type.
6337 // For record types, this is done by the AbstractClassUsageDiagnoser once
6338 // the class has been completely parsed.
6339 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006340 SemaRef.RequireNonAbstractType(
6341 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6342 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006343 D.setInvalidType();
6344
6345 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6346 // This is a C++ constructor declaration.
6347 assert(DC->isRecord() &&
6348 "Constructors can only be declared in a member context");
6349
6350 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6351 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006352 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006353 R, TInfo, isExplicit, isInline,
6354 /*isImplicitlyDeclared=*/false,
6355 isConstexpr);
6356
6357 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6358 // This is a C++ destructor declaration.
6359 if (DC->isRecord()) {
6360 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6361 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6362 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6363 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006364 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006365 NameInfo, R, TInfo, isInline,
6366 /*isImplicitlyDeclared=*/false);
6367
6368 // If the class is complete, then we now create the implicit exception
6369 // specification. If the class is incomplete or dependent, we can't do
6370 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006371 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006372 Record->getDefinition() && !Record->isBeingDefined() &&
6373 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6374 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6375 }
6376
6377 IsVirtualOkay = true;
6378 return NewDD;
6379
6380 } else {
6381 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6382 D.setInvalidType();
6383
6384 // Create a FunctionDecl to satisfy the function definition parsing
6385 // code path.
6386 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006387 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006388 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006389 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006390 /*hasPrototype=*/true, isConstexpr);
6391 }
6392
6393 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6394 if (!DC->isRecord()) {
6395 SemaRef.Diag(D.getIdentifierLoc(),
6396 diag::err_conv_function_not_member);
6397 return 0;
6398 }
6399
6400 SemaRef.CheckConversionDeclarator(D, R, SC);
6401 IsVirtualOkay = true;
6402 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006403 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006404 R, TInfo, isInline, isExplicit,
6405 isConstexpr, SourceLocation());
6406
6407 } else if (DC->isRecord()) {
6408 // If the name of the function is the same as the name of the record,
6409 // then this must be an invalid constructor that has a return type.
6410 // (The parser checks for a return type and makes the declarator a
6411 // constructor if it has no return type).
6412 if (Name.getAsIdentifierInfo() &&
6413 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6414 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6415 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6416 << SourceRange(D.getIdentifierLoc());
6417 return 0;
6418 }
6419
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006420 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006421 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6422 cast<CXXRecordDecl>(DC),
6423 D.getLocStart(), NameInfo, R,
6424 TInfo, SC, isInline,
6425 isConstexpr, SourceLocation());
6426 IsVirtualOkay = !Ret->isStatic();
6427 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006428 } else {
6429 // Determine whether the function was written with a
6430 // prototype. This true when:
6431 // - we're in C++ (where every function has a prototype),
6432 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006433 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006434 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006435 true/*HasPrototype*/, isConstexpr);
6436 }
6437}
6438
Matt Arsenaultefb38192013-07-23 01:23:36 +00006439enum OpenCLParamType {
6440 ValidKernelParam,
6441 PtrPtrKernelParam,
6442 PtrKernelParam,
David Tweedababa8f2014-03-27 16:34:11 +00006443 PrivatePtrKernelParam,
Matt Arsenaultefb38192013-07-23 01:23:36 +00006444 InvalidKernelParam,
6445 RecordKernelParam
6446};
6447
6448static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6449 if (PT->isPointerType()) {
6450 QualType PointeeType = PT->getPointeeType();
David Tweedababa8f2014-03-27 16:34:11 +00006451 if (PointeeType->isPointerType())
6452 return PtrPtrKernelParam;
6453 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6454 : PtrKernelParam;
Matt Arsenaultefb38192013-07-23 01:23:36 +00006455 }
6456
6457 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6458 // be used as builtin types.
6459
6460 if (PT->isImageType())
6461 return PtrKernelParam;
6462
6463 if (PT->isBooleanType())
6464 return InvalidKernelParam;
6465
6466 if (PT->isEventT())
6467 return InvalidKernelParam;
6468
6469 if (PT->isHalfType())
6470 return InvalidKernelParam;
6471
6472 if (PT->isRecordType())
6473 return RecordKernelParam;
6474
6475 return ValidKernelParam;
6476}
6477
6478static void checkIsValidOpenCLKernelParameter(
6479 Sema &S,
6480 Declarator &D,
6481 ParmVarDecl *Param,
6482 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6483 QualType PT = Param->getType();
6484
6485 // Cache the valid types we encounter to avoid rechecking structs that are
6486 // used again
6487 if (ValidTypes.count(PT.getTypePtr()))
6488 return;
6489
6490 switch (getOpenCLKernelParameterType(PT)) {
6491 case PtrPtrKernelParam:
6492 // OpenCL v1.2 s6.9.a:
6493 // A kernel function argument cannot be declared as a
6494 // pointer to a pointer type.
6495 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6496 D.setInvalidType();
6497 return;
6498
David Tweedababa8f2014-03-27 16:34:11 +00006499 case PrivatePtrKernelParam:
6500 // OpenCL v1.2 s6.9.a:
6501 // A kernel function argument cannot be declared as a
6502 // pointer to the private address space.
6503 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6504 D.setInvalidType();
6505 return;
6506
Matt Arsenaultefb38192013-07-23 01:23:36 +00006507 // OpenCL v1.2 s6.9.k:
6508 // Arguments to kernel functions in a program cannot be declared with the
6509 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6510 // uintptr_t or a struct and/or union that contain fields declared to be
6511 // one of these built-in scalar types.
6512
6513 case InvalidKernelParam:
6514 // OpenCL v1.2 s6.8 n:
6515 // A kernel function argument cannot be declared
6516 // of event_t type.
6517 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6518 D.setInvalidType();
6519 return;
6520
6521 case PtrKernelParam:
6522 case ValidKernelParam:
6523 ValidTypes.insert(PT.getTypePtr());
6524 return;
6525
6526 case RecordKernelParam:
6527 break;
6528 }
6529
6530 // Track nested structs we will inspect
6531 SmallVector<const Decl *, 4> VisitStack;
6532
6533 // Track where we are in the nested structs. Items will migrate from
6534 // VisitStack to HistoryStack as we do the DFS for bad field.
6535 SmallVector<const FieldDecl *, 4> HistoryStack;
6536 HistoryStack.push_back((const FieldDecl *) 0);
6537
6538 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6539 VisitStack.push_back(PD);
6540
6541 assert(VisitStack.back() && "First decl null?");
6542
6543 do {
6544 const Decl *Next = VisitStack.pop_back_val();
6545 if (!Next) {
6546 assert(!HistoryStack.empty());
6547 // Found a marker, we have gone up a level
6548 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6549 ValidTypes.insert(Hist->getType().getTypePtr());
6550
6551 continue;
6552 }
6553
6554 // Adds everything except the original parameter declaration (which is not a
6555 // field itself) to the history stack.
6556 const RecordDecl *RD;
6557 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6558 HistoryStack.push_back(Field);
6559 RD = Field->getType()->castAs<RecordType>()->getDecl();
6560 } else {
6561 RD = cast<RecordDecl>(Next);
6562 }
6563
6564 // Add a null marker so we know when we've gone back up a level
6565 VisitStack.push_back((const Decl *) 0);
6566
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006567 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006568 QualType QT = FD->getType();
6569
6570 if (ValidTypes.count(QT.getTypePtr()))
6571 continue;
6572
6573 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6574 if (ParamType == ValidKernelParam)
6575 continue;
6576
6577 if (ParamType == RecordKernelParam) {
6578 VisitStack.push_back(FD);
6579 continue;
6580 }
6581
6582 // OpenCL v1.2 s6.9.p:
6583 // Arguments to kernel functions that are declared to be a struct or union
6584 // do not allow OpenCL objects to be passed as elements of the struct or
6585 // union.
David Tweedababa8f2014-03-27 16:34:11 +00006586 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6587 ParamType == PrivatePtrKernelParam) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006588 S.Diag(Param->getLocation(),
6589 diag::err_record_with_pointers_kernel_param)
6590 << PT->isUnionType()
6591 << PT;
6592 } else {
6593 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6594 }
6595
6596 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6597 << PD->getDeclName();
6598
6599 // We have an error, now let's go back up through history and show where
6600 // the offending field came from
6601 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6602 E = HistoryStack.end(); I != E; ++I) {
6603 const FieldDecl *OuterField = *I;
6604 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6605 << OuterField->getType();
6606 }
6607
6608 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6609 << QT->isPointerType()
6610 << QT;
6611 D.setInvalidType();
6612 return;
6613 }
6614 } while (!VisitStack.empty());
6615}
6616
Mike Stump11289f42009-09-09 15:08:12 +00006617NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006618Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006619 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006620 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006621 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006622 QualType R = TInfo->getType();
6623
Zhongxing Xubece5d62009-01-16 01:13:29 +00006624 assert(R.getTypePtr()->isFunctionType());
6625
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006626 // TODO: consider using NameInfo for diagnostic.
6627 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6628 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006629 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006630
Richard Smithb4a9e862013-04-12 22:46:28 +00006631 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6632 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6633 diag::err_invalid_thread)
6634 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006635
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006636 if (D.isFirstDeclarationOfMember())
6637 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006638
Douglas Gregor513e63c2010-12-10 19:28:19 +00006639 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006640 FunctionTemplateDecl *FunctionTemplate = 0;
6641 bool isExplicitSpecialization = false;
6642 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006643
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006644 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006645 bool HasExplicitTemplateArgs = false;
6646 TemplateArgumentListInfo TemplateArgs;
6647
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006648 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006649
Richard Smith541b38b2013-09-20 01:15:31 +00006650 DeclContext *OriginalDC = DC;
6651 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6652
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006653 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6654 isVirtualOkay);
6655 if (!NewFD) return 0;
6656
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006657 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6658 NewFD->setTopLevelDeclInObjCContainer();
6659
Richard Smith541b38b2013-09-20 01:15:31 +00006660 // Set the lexical context. If this is a function-scope declaration, or has a
6661 // C++ scope specifier, or is the object of a friend declaration, the lexical
6662 // context will be different from the semantic context.
6663 NewFD->setLexicalDeclContext(CurContext);
6664
6665 if (IsLocalExternDecl)
6666 NewFD->setLocalExternDecl();
6667
David Blaikiebbafb8a2012-03-11 07:00:24 +00006668 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006669 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006670 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6671 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006672 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006673 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006674 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006675 // C++ [class.friend]p5
6676 // A function can be defined in a friend declaration of a
6677 // class . . . . Such a function is implicitly inline.
6678 NewFD->setImplicitlyInline();
6679 }
6680
John McCalldb632ac2012-09-25 07:32:39 +00006681 // If this is a method defined in an __interface, and is not a constructor
6682 // or an overloaded operator, then set the pure flag (isVirtual will already
6683 // return true).
6684 if (const CXXRecordDecl *Parent =
6685 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6686 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006687 NewFD->setPure(true);
6688 }
6689
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006690 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006691 isExplicitSpecialization = false;
6692 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006693 if (D.isInvalidType())
6694 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006695
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006696 // Match up the template parameter lists with the scope specifier, then
6697 // determine whether we have a template or a template specialization.
6698 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006699 if (TemplateParameterList *TemplateParams =
6700 MatchTemplateParametersToScopeSpecifier(
6701 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00006702 D.getCXXScopeSpec(),
6703 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6704 ? D.getName().TemplateId
6705 : 0,
6706 TemplateParamLists, isFriend, isExplicitSpecialization,
6707 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006708 if (TemplateParams->size() > 0) {
6709 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006710
Abramo Bagnara60804e12011-03-18 15:16:37 +00006711 // Check that we can declare a template here.
6712 if (CheckTemplateDeclScope(S, TemplateParams))
6713 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006714
Abramo Bagnara60804e12011-03-18 15:16:37 +00006715 // A destructor cannot be a template.
6716 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6717 Diag(NewFD->getLocation(), diag::err_destructor_template);
6718 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006719 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006720
6721 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006722 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006723 // now that we know what the current instantiation is.
6724 if (DC->isDependentContext()) {
6725 ContextRAII SavedContext(*this, DC);
6726 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6727 Invalid = true;
6728 }
6729
John McCall1f0479e2010-03-24 08:27:58 +00006730
Abramo Bagnara60804e12011-03-18 15:16:37 +00006731 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6732 NewFD->getLocation(),
6733 Name, TemplateParams,
6734 NewFD);
6735 FunctionTemplate->setLexicalDeclContext(CurContext);
6736 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6737
6738 // For source fidelity, store the other template param lists.
6739 if (TemplateParamLists.size() > 1) {
6740 NewFD->setTemplateParameterListsInfo(Context,
6741 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006742 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006743 }
6744 } else {
6745 // This is a function template specialization.
6746 isFunctionTemplateSpecialization = true;
6747 // For source fidelity, store all the template param lists.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006748 if (TemplateParamLists.size() > 0)
6749 NewFD->setTemplateParameterListsInfo(Context,
6750 TemplateParamLists.size(),
6751 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006752
6753 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6754 if (isFriend) {
6755 // We want to remove the "template<>", found here.
6756 SourceRange RemoveRange = TemplateParams->getSourceRange();
6757
6758 // If we remove the template<> and the name is not a
6759 // template-id, we're actually silently creating a problem:
6760 // the friend declaration will refer to an untemplated decl,
6761 // and clearly the user wants a template specialization. So
6762 // we need to insert '<>' after the name.
6763 SourceLocation InsertLoc;
6764 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6765 InsertLoc = D.getName().getSourceRange().getEnd();
6766 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6767 }
6768
6769 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6770 << Name << RemoveRange
6771 << FixItHint::CreateRemoval(RemoveRange)
6772 << FixItHint::CreateInsertion(InsertLoc, "<>");
6773 }
6774 }
6775 }
6776 else {
6777 // All template param lists were matched against the scope specifier:
6778 // this is NOT (an explicit specialization of) a template.
6779 if (TemplateParamLists.size() > 0)
6780 // For source fidelity, store all the template param lists.
6781 NewFD->setTemplateParameterListsInfo(Context,
6782 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006783 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006784 }
6785
6786 if (Invalid) {
6787 NewFD->setInvalidDecl();
6788 if (FunctionTemplate)
6789 FunctionTemplate->setInvalidDecl();
6790 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006791
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006792 // C++ [dcl.fct.spec]p5:
6793 // The virtual specifier shall only be used in declarations of
6794 // nonstatic class member functions that appear within a
6795 // member-specification of a class declaration; see 10.3.
6796 //
6797 if (isVirtual && !NewFD->isInvalidDecl()) {
6798 if (!isVirtualOkay) {
6799 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6800 diag::err_virtual_non_function);
6801 } else if (!CurContext->isRecord()) {
6802 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006803 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6804 diag::err_virtual_out_of_class)
6805 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6806 } else if (NewFD->getDescribedFunctionTemplate()) {
6807 // C++ [temp.mem]p3:
6808 // A member function template shall not be virtual.
6809 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6810 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006811 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6812 } else {
6813 // Okay: Add virtual to the method.
6814 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006815 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006816
6817 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006818 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006819 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006820 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006821
Richard Smithc1564702013-11-15 02:58:23 +00006822 if (getLangOpts().CPlusPlus1y &&
6823 (NewFD->isDependentContext() ||
6824 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006825 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006826 // If the function template is referenced directly (for instance, as a
6827 // member of the current instantiation), pretend it has a dependent type.
6828 // This is not really justified by the standard, but is the only sane
6829 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006830 // FIXME: For a friend function, we have not marked the function as being
6831 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006832 const FunctionProtoType *FPT =
6833 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006834 QualType Result =
6835 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006836 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006837 FPT->getExtProtoInfo()));
6838 }
6839
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006840 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006841 // The inline specifier shall not appear on a block scope function
6842 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006843 if (isInline && !NewFD->isInvalidDecl()) {
6844 if (CurContext->isFunctionOrMethod()) {
6845 // 'inline' is not allowed on block scope function declaration.
6846 Diag(D.getDeclSpec().getInlineSpecLoc(),
6847 diag::err_inline_declaration_block_scope) << Name
6848 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6849 }
6850 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006851
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006852 // C++ [dcl.fct.spec]p6:
6853 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006854 // constructor or conversion function within its class definition;
6855 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006856 if (isExplicit && !NewFD->isInvalidDecl()) {
6857 if (!CurContext->isRecord()) {
6858 // 'explicit' was specified outside of the class.
6859 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6860 diag::err_explicit_out_of_class)
6861 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6862 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6863 !isa<CXXConversionDecl>(NewFD)) {
6864 // 'explicit' was specified on a function that wasn't a constructor
6865 // or conversion function.
6866 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6867 diag::err_explicit_non_ctor_or_conv_function)
6868 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6869 }
6870 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006871
Richard Smitha77a0a62011-08-15 21:04:07 +00006872 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006873 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006874 // are implicitly inline.
6875 NewFD->setImplicitlyInline();
6876
Richard Smith574f4f62013-01-14 05:37:29 +00006877 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006878 // be either constructors or to return a literal type. Therefore,
6879 // destructors cannot be declared constexpr.
6880 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006881 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006882 }
6883
Douglas Gregor26701a42011-09-09 02:06:17 +00006884 // If __module_private__ was specified, mark the function accordingly.
6885 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006886 if (isFunctionTemplateSpecialization) {
6887 SourceLocation ModulePrivateLoc
6888 = D.getDeclSpec().getModulePrivateSpecLoc();
6889 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6890 << 0
6891 << FixItHint::CreateRemoval(ModulePrivateLoc);
6892 } else {
6893 NewFD->setModulePrivate();
6894 if (FunctionTemplate)
6895 FunctionTemplate->setModulePrivate();
6896 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006897 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006898
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006899 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006900 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006901 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006902 FunctionTemplate->setAccess(AS_public);
6903 }
Richard Smith64017682013-07-17 23:53:16 +00006904 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006905 NewFD->setAccess(AS_public);
6906 }
6907
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006908 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006909 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6910 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006911 switch (D.getFunctionDefinitionKind()) {
6912 case FDK_Declaration:
6913 case FDK_Definition:
6914 break;
6915
6916 case FDK_Defaulted:
6917 NewFD->setDefaulted();
6918 break;
6919
6920 case FDK_Deleted:
6921 NewFD->setDeletedAsWritten();
6922 break;
6923 }
6924
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006925 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6926 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006927 // C++ [class.mfct]p2:
6928 // A member function may be defined (8.4) in its class definition, in
6929 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006930 NewFD->setImplicitlyInline();
6931 }
6932
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006933 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6934 !CurContext->isRecord()) {
6935 // C++ [class.static]p1:
6936 // A data or function member of a class may be declared static
6937 // in a class definition, in which case it is a static member of
6938 // the class.
6939
6940 // Complain about the 'static' specifier if it's on an out-of-line
6941 // member function definition.
6942 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6943 diag::err_static_out_of_line)
6944 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6945 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006946
6947 // C++11 [except.spec]p15:
6948 // A deallocation function with no exception-specification is treated
6949 // as if it were specified with noexcept(true).
6950 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6951 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6952 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006953 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006954 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6955 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00006956 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006957 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006958 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006959 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006960
6961 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006962 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006963 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006964 isExplicitSpecialization ||
6965 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006966
Zhongxing Xubece5d62009-01-16 01:13:29 +00006967 // Handle GNU asm-label extension (encoded as an attribute).
6968 if (Expr *E = (Expr*) D.getAsmLabel()) {
6969 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006970 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006971 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006972 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006973 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6974 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6975 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6976 if (I != ExtnameUndeclaredIdentifiers.end()) {
6977 NewFD->addAttr(I->second);
6978 ExtnameUndeclaredIdentifiers.erase(I);
6979 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006980 }
6981
Chris Lattner9af40c12009-04-25 06:12:16 +00006982 // Copy the parameter declarations from the declarator D to the function
6983 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006984 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006985 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006986 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006987
Zhongxing Xubece5d62009-01-16 01:13:29 +00006988 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6989 // function that takes no arguments, not a function that takes a
6990 // single void argument.
6991 // We let through "const void" here because Sema::GetTypeForDeclarator
6992 // already checks for that case.
Alp Tokerc5350722014-02-26 22:27:52 +00006993 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6994 FTI.Params[0].Param &&
6995 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006996 // Empty arg list, don't push any params.
Alp Tokerc5350722014-02-26 22:27:52 +00006997 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) {
6998 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
6999 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007000 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7001 Param->setDeclContext(NewFD);
7002 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00007003
7004 if (Param->isInvalidDecl())
7005 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007006 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007007 }
Mike Stump11289f42009-09-09 15:08:12 +00007008
John McCall9dd450b2009-09-21 23:43:11 +00007009 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00007010 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00007011 // following example, we'll need to synthesize (unnamed)
7012 // parameters for use in the declaration.
7013 //
7014 // @code
7015 // typedef void fn(int);
7016 // fn f;
7017 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00007018
Chris Lattner47c0d002009-04-25 06:03:53 +00007019 // Synthesize a parameter for each argument type.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007020 for (const auto &AI : FT->param_types()) {
John McCalla3ccba02010-06-04 11:21:44 +00007021 ParmVarDecl *Param =
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007022 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00007023 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00007024 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00007025 }
Chris Lattner49303b22009-04-25 18:38:18 +00007026 } else {
7027 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7028 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00007029 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00007030
Chris Lattner9af40c12009-04-25 06:12:16 +00007031 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00007032 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00007033
James Molloy6f8780b2012-02-29 10:24:19 +00007034 // Find all anonymous symbols defined during the declaration of this function
7035 // and add to NewFD. This lets us track decls such 'enum Y' in:
7036 //
7037 // void f(enum Y {AA} x) {}
7038 //
7039 // which would otherwise incorrectly end up in the translation unit scope.
7040 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7041 DeclsInPrototypeScope.clear();
7042
Richard Smithdebc59d2013-01-30 05:45:05 +00007043 if (D.getDeclSpec().isNoreturnSpecified())
7044 NewFD->addAttr(
7045 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00007046 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00007047
Richard Smith84208dc2012-03-13 05:56:40 +00007048 // Functions returning a variably modified type violate C99 6.7.5.2p2
7049 // because all functions have linkage.
7050 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00007051 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00007052 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7053 NewFD->setInvalidDecl();
7054 }
7055
Warren Huntc3b18962014-04-08 22:30:47 +00007056 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7057 !NewFD->hasAttr<SectionAttr>()) {
7058 NewFD->addAttr(
7059 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7060 CodeSegStack.CurrentValue->getString(),
7061 CodeSegStack.CurrentPragmaLocation));
7062 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7063 PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7064 NewFD->dropAttr<SectionAttr>();
7065 }
7066
Rafael Espindolac67f2232012-05-10 02:50:16 +00007067 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00007068 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00007069
Alp Toker314cc812014-01-25 16:55:45 +00007070 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007071 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7072 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7073 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7074 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007075 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
David Blaikie080a61c2014-02-09 07:24:41 +00007076 // Attach WarnUnusedResult to functions returning types with that attribute.
7077 // Don't apply the attribute to that type's own non-static member functions
7078 // (to avoid warning on things like assignment operators)
7079 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00007080 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007081 }
7082
Joey Gouly16cb99d2014-01-06 11:26:18 +00007083 if (getLangOpts().OpenCL) {
7084 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7085 // type declaration will generate a compilation error.
7086 unsigned AddressSpace = RetType.getAddressSpace();
7087 if (AddressSpace == LangAS::opencl_local ||
7088 AddressSpace == LangAS::opencl_global ||
7089 AddressSpace == LangAS::opencl_constant) {
7090 Diag(NewFD->getLocation(),
7091 diag::err_opencl_return_value_with_address_space);
7092 NewFD->setInvalidDecl();
7093 }
7094 }
7095
David Blaikiebbafb8a2012-03-11 07:00:24 +00007096 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007097 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007098 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007099 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7100 CheckMain(NewFD, D.getDeclSpec());
7101
David Majnemerc729b0b2013-09-16 22:44:20 +00007102 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7103 CheckMSVCRTEntryPoint(NewFD);
7104
David Majnemer027f9c42013-07-06 02:13:46 +00007105 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007106 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7107 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007108 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007109 // Make graceful recovery from an invalid redeclaration.
7110 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007111 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007112 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7113 "previous declaration set still overloaded");
7114 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007115 // C++11 [replacement.functions]p3:
7116 // The program's definitions shall not be specified as inline.
7117 //
7118 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7119 //
7120 // Suppress the diagnostic if the function is __attribute__((used)), since
7121 // that forces an external definition to be emitted.
7122 if (D.getDeclSpec().isInlineSpecified() &&
7123 NewFD->isReplaceableGlobalAllocationFunction() &&
7124 !NewFD->hasAttr<UsedAttr>())
7125 Diag(D.getDeclSpec().getInlineSpecLoc(),
7126 diag::ext_operator_new_delete_declared_inline)
7127 << NewFD->getDeclName();
7128
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007129 // If the declarator is a template-id, translate the parser's template
7130 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007131 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7132 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7133 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7134 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007135 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007136 TemplateId->NumArgs);
7137 translateTemplateArguments(TemplateArgsPtr,
7138 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007139
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007140 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007141
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007142 if (NewFD->isInvalidDecl()) {
7143 HasExplicitTemplateArgs = false;
7144 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007145 // Function template with explicit template arguments.
7146 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7147 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7148
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007149 HasExplicitTemplateArgs = false;
John McCallf7cfb222010-10-13 05:45:15 +00007150 } else {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007151 assert((isFunctionTemplateSpecialization ||
7152 D.getDeclSpec().isFriendSpecified()) &&
7153 "should have a 'template<>' for this decl");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007154 // "friend void foo<>(int);" is an implicit specialization decl.
7155 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007156 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007157 } else if (isFriend && isFunctionTemplateSpecialization) {
7158 // This combination is only possible in a recovery case; the user
7159 // wrote something like:
7160 // template <> friend void foo(int);
7161 // which we're recovering from as if the user had written:
7162 // friend void foo<>(int);
7163 // Go ahead and fake up a template id.
7164 HasExplicitTemplateArgs = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00007165 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007166 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007167 }
John McCallf7cfb222010-10-13 05:45:15 +00007168
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007169 // If it's a friend (and only if it's a friend), it's possible
7170 // that either the specialized function type or the specialized
7171 // template is dependent, and therefore matching will fail. In
7172 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007173 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007174 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007175 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7176 TemplateSpecializationType::anyDependentTemplateArguments(
7177 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7178 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007179 assert(HasExplicitTemplateArgs &&
7180 "friend function specialization without template args");
7181 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7182 Previous))
7183 NewFD->setInvalidDecl();
7184 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007185 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007186 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007187 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007188 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007189 diag::ext_function_specialization_in_class :
7190 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007191 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007192 } else if (CheckFunctionTemplateSpecialization(NewFD,
7193 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7194 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007195 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007196
7197 // C++ [dcl.stc]p1:
7198 // A storage-class-specifier shall not be specified in an explicit
7199 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007200 FunctionTemplateSpecializationInfo *Info =
7201 NewFD->getTemplateSpecializationInfo();
7202 if (Info && SC != SC_None) {
7203 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007204 Diag(NewFD->getLocation(),
7205 diag::err_explicit_specialization_inconsistent_storage_class)
7206 << SC
7207 << FixItHint::CreateRemoval(
7208 D.getDeclSpec().getStorageClassSpecLoc());
7209
7210 else
7211 Diag(NewFD->getLocation(),
7212 diag::ext_explicit_specialization_storage_class)
7213 << FixItHint::CreateRemoval(
7214 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007215 }
7216
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007217 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7218 if (CheckMemberSpecialization(NewFD, Previous))
7219 NewFD->setInvalidDecl();
7220 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007221
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007222 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007223 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007224 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7225 CheckMain(NewFD, D.getDeclSpec());
7226
David Majnemerc729b0b2013-09-16 22:44:20 +00007227 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7228 CheckMSVCRTEntryPoint(NewFD);
7229
Nico Weber7607fce2013-12-21 00:49:51 +00007230 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007231 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7232 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007233 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007234
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007235 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007236 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7237 "previous declaration set still overloaded");
7238
7239 NamedDecl *PrincipalDecl = (FunctionTemplate
7240 ? cast<NamedDecl>(FunctionTemplate)
7241 : NewFD);
7242
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007243 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007244 AccessSpecifier Access = AS_public;
7245 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007246 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007247
7248 NewFD->setAccess(Access);
7249 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007250 }
7251
7252 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7253 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7254 PrincipalDecl->setNonMemberOperator();
7255
7256 // If we have a function template, check the template parameter
7257 // list. This will check and merge default template arguments.
7258 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007259 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007260 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007261 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007262 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007263 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007264 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007265 ? TPC_FriendFunctionTemplateDefinition
7266 : TPC_FriendFunctionTemplate)
7267 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007268 DC && DC->isRecord() &&
7269 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007270 ? TPC_ClassTemplateMember
7271 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007272 }
7273
7274 if (NewFD->isInvalidDecl()) {
7275 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007276 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007277 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007278 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007279 // Fake up an access specifier if it's supposed to be a class member.
7280 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7281 NewFD->setAccess(AS_public);
7282
7283 // Qualified decls generally require a previous declaration.
7284 if (D.getCXXScopeSpec().isSet()) {
7285 // ...with the major exception of templated-scope or
7286 // dependent-scope friend declarations.
7287
7288 // TODO: we currently also suppress this check in dependent
7289 // contexts because (1) the parameter depth will be off when
7290 // matching friend templates and (2) we might actually be
7291 // selecting a friend based on a dependent factor. But there
7292 // are situations where these conditions don't apply and we
7293 // can actually do this check immediately.
7294 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007295 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007296 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7297 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007298 // ignore these
7299 } else {
7300 // The user tried to provide an out-of-line definition for a
7301 // function that is a member of a class or namespace, but there
7302 // was no such member function declared (C++ [class.mfct]p2,
7303 // C++ [namespace.memdef]p2). For example:
7304 //
7305 // class X {
7306 // void f() const;
7307 // };
7308 //
7309 // void X::f() { } // ill-formed
7310 //
7311 // Complain about this problem, and attempt to suggest close
7312 // matches (e.g., those that differ only in cv-qualifiers and
7313 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007314
Richard Smith114394f2013-08-09 04:35:01 +00007315 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7316 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007317 AddToScope = ExtraArgs.AddToScope;
7318 return Result;
7319 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007320 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007321
7322 // Unqualified local friend declarations are required to resolve
7323 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007324 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007325 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7326 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007327 AddToScope = ExtraArgs.AddToScope;
7328 return Result;
7329 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007330 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007331
Richard Smitha2302242013-12-05 07:51:02 +00007332 } else if (!D.isFunctionDefinition() &&
7333 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007334 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007335 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007336 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007337 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007338 // Note that this is not the case for explicit specializations of
7339 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007340 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7341 // extension for compatibility with old SWIG code which likes to
7342 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007343 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7344 << D.getCXXScopeSpec().getRange();
7345 }
7346 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007347
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007348 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007349 checkAttributesAfterMerging(*this, *NewFD);
7350
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007351 AddKnownFunctionAttributes(NewFD);
7352
Douglas Gregor72609052010-08-06 13:50:58 +00007353 if (NewFD->hasAttr<OverloadableAttr>() &&
7354 !NewFD->getType()->getAs<FunctionProtoType>()) {
7355 Diag(NewFD->getLocation(),
7356 diag::err_attribute_overloadable_no_prototype)
7357 << NewFD;
7358
7359 // Turn this into a variadic function with no parameters.
7360 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007361 FunctionProtoType::ExtProtoInfo EPI(
7362 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007363 EPI.Variadic = true;
7364 EPI.ExtInfo = FT->getExtInfo();
7365
Alp Toker314cc812014-01-25 16:55:45 +00007366 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007367 NewFD->setType(R);
7368 }
7369
Eli Friedman570024a2010-08-05 06:57:20 +00007370 // If there's a #pragma GCC visibility in scope, and this isn't a class
7371 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007372 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007373 AddPushedVisibilityAttribute(NewFD);
7374
John McCall32f5fe12011-09-30 05:12:12 +00007375 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7376 // marking the function.
7377 AddCFAuditedAttribute(NewFD);
7378
Richard Smithac974a32013-06-30 09:48:50 +00007379 // If this is the first declaration of an extern C variable, update
7380 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007381 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007382 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007383 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007384
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007385 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007386 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007387
Nico Rieck82f0b062014-03-31 14:56:15 +00007388 if (D.isRedeclaration() && !Previous.empty()) {
7389 checkDLLAttributeRedeclaration(
7390 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7391 isExplicitSpecialization || isFunctionTemplateSpecialization);
7392 }
7393
David Blaikiebbafb8a2012-03-11 07:00:24 +00007394 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007395 if (FunctionTemplate) {
7396 if (NewFD->isInvalidDecl())
7397 FunctionTemplate->setInvalidDecl();
7398 return FunctionTemplate;
7399 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007400 }
Mike Stump11289f42009-09-09 15:08:12 +00007401
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007402 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007403 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7404 if ((getLangOpts().OpenCLVersion >= 120)
7405 && (SC == SC_Static)) {
7406 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7407 D.setInvalidType();
7408 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007409
7410 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007411 if (!NewFD->getReturnType()->isVoidType()) {
Tanya Lattner0f864332013-01-30 19:48:52 +00007412 Diag(D.getIdentifierLoc(),
7413 diag::err_expected_kernel_void_return_type);
7414 D.setInvalidType();
7415 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007416
7417 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007418 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007419 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007420 }
7421
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007422 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007423
David Blaikiebbafb8a2012-03-11 07:00:24 +00007424 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007425 if (IdentifierInfo *II = NewFD->getIdentifier())
7426 if (!NewFD->isInvalidDecl() &&
7427 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7428 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007429 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007430 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7431
7432 Context.setcudaConfigureCallDecl(NewFD);
7433 }
7434 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007435
7436 // Here we have an function template explicit specialization at class scope.
7437 // The actually specialization will be postponed to template instatiation
7438 // time via the ClassScopeFunctionSpecializationDecl node.
7439 if (isDependentClassScopeExplicitSpecialization) {
7440 ClassScopeFunctionSpecializationDecl *NewSpec =
7441 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007442 Context, CurContext, SourceLocation(),
7443 cast<CXXMethodDecl>(NewFD),
7444 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007445 CurContext->addDecl(NewSpec);
7446 AddToScope = false;
7447 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007448
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007449 return NewFD;
7450}
7451
7452/// \brief Perform semantic checking of a new function declaration.
7453///
7454/// Performs semantic analysis of the new function declaration
7455/// NewFD. This routine performs all semantic checking that does not
7456/// require the actual declarator involved in the declaration, and is
7457/// used both for the declaration of functions as they are parsed
7458/// (called via ActOnDeclarator) and for the declaration of functions
7459/// that have been instantiated via C++ template instantiation (called
7460/// via InstantiateDecl).
7461///
James Dennettffad8b72012-06-22 08:10:18 +00007462/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007463/// an explicit specialization of the previous declaration.
7464///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007465/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007466///
James Dennettffad8b72012-06-22 08:10:18 +00007467/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007468bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007469 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007470 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007471 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7472 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007473
Richard Smith1c34fb72013-08-13 18:18:50 +00007474 // Determine whether the type of this function should be merged with
7475 // a previous visible declaration. This never happens for functions in C++,
7476 // and always happens in C if the previous declaration was visible.
7477 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7478 !Previous.isShadowed();
7479
Douglas Gregor3552dab2013-01-09 00:47:56 +00007480 // Filter out any non-conflicting previous declarations.
7481 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7482
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007483 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007484 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007485
Douglas Gregore62c0a42009-02-24 01:23:02 +00007486 // Merge or overload the declaration with an existing declaration of
7487 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007488 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007489 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007490 // a declaration that requires merging. If it's an overload,
7491 // there's no more work to do here; we'll just add the new
7492 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007493 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007494 NamedDecl *Candidate = Previous.getFoundDecl();
7495 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7496 Redeclaration = true;
7497 OldDecl = Candidate;
7498 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007499 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007500 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7501 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007502 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007503 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007504 break;
7505
7506 case Ovl_NonFunction:
7507 Redeclaration = true;
7508 break;
7509
7510 case Ovl_Overload:
7511 Redeclaration = false;
7512 break;
John McCall1f82f242009-11-18 22:49:29 +00007513 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007514
David Blaikiebbafb8a2012-03-11 07:00:24 +00007515 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007516 // If a function name is overloadable in C, then every function
7517 // with that name must be marked "overloadable".
7518 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7519 << Redeclaration << NewFD;
7520 NamedDecl *OverloadedDecl = 0;
7521 if (Redeclaration)
7522 OverloadedDecl = OldDecl;
7523 else if (!Previous.empty())
7524 OverloadedDecl = Previous.getRepresentativeDecl();
7525 if (OverloadedDecl)
7526 Diag(OverloadedDecl->getLocation(),
7527 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007528 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007529 }
John McCall1f82f242009-11-18 22:49:29 +00007530 }
Richard Smith574f4f62013-01-14 05:37:29 +00007531 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007532
Richard Smithac974a32013-06-30 09:48:50 +00007533 // Check for a previous extern "C" declaration with this name.
7534 if (!Redeclaration &&
7535 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7536 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7537 if (!Previous.empty()) {
7538 // This is an extern "C" declaration with the same name as a previous
7539 // declaration, and thus redeclares that entity...
7540 Redeclaration = true;
7541 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007542 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007543
7544 // ... except in the presence of __attribute__((overloadable)).
7545 if (OldDecl->hasAttr<OverloadableAttr>()) {
7546 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7547 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7548 << Redeclaration << NewFD;
7549 Diag(Previous.getFoundDecl()->getLocation(),
7550 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007551 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007552 }
7553 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7554 Redeclaration = false;
7555 OldDecl = 0;
7556 }
7557 }
7558 }
7559 }
7560
Richard Smith574f4f62013-01-14 05:37:29 +00007561 // C++11 [dcl.constexpr]p8:
7562 // A constexpr specifier for a non-static member function that is not
7563 // a constructor declares that member function to be const.
7564 //
7565 // This needs to be delayed until we know whether this is an out-of-line
7566 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007567 //
7568 // This rule is not present in C++1y, so we produce a backwards
7569 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007570 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007571 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7572 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007573 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Alp Tokera2794f92014-01-22 07:29:52 +00007574 CXXMethodDecl *OldMD = 0;
7575 if (OldDecl)
7576 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007577 if (!OldMD || !OldMD->isStatic()) {
7578 const FunctionProtoType *FPT =
7579 MD->getType()->castAs<FunctionProtoType>();
7580 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7581 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007582 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007583 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007584
7585 // Warn that we did this, if we're not performing template instantiation.
7586 // In that case, we'll have warned already when the template was defined.
7587 if (ActiveTemplateInstantiations.empty()) {
7588 SourceLocation AddConstLoc;
7589 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7590 .IgnoreParens().getAs<FunctionTypeLoc>())
7591 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7592
7593 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7594 << FixItHint::CreateInsertion(AddConstLoc, " const");
7595 }
Richard Smith574f4f62013-01-14 05:37:29 +00007596 }
7597 }
7598
7599 if (Redeclaration) {
7600 // NewFD and OldDecl represent declarations that need to be
7601 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007602 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007603 NewFD->setInvalidDecl();
7604 return Redeclaration;
7605 }
7606
7607 Previous.clear();
7608 Previous.addDecl(OldDecl);
7609
7610 if (FunctionTemplateDecl *OldTemplateDecl
7611 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7612 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7613 FunctionTemplateDecl *NewTemplateDecl
7614 = NewFD->getDescribedFunctionTemplate();
7615 assert(NewTemplateDecl && "Template/non-template mismatch");
7616 if (CXXMethodDecl *Method
7617 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7618 Method->setAccess(OldTemplateDecl->getAccess());
7619 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007620 }
Richard Smith574f4f62013-01-14 05:37:29 +00007621
7622 // If this is an explicit specialization of a member that is a function
7623 // template, mark it as a member specialization.
7624 if (IsExplicitSpecialization &&
7625 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7626 NewTemplateDecl->setMemberSpecialization();
7627 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007628 }
Richard Smith574f4f62013-01-14 05:37:29 +00007629
7630 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007631 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007632 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007633
7634 if (isa<CXXMethodDecl>(NewFD)) {
7635 // A valid redeclaration of a C++ method must be out-of-line,
7636 // but (unfortunately) it's not necessarily a definition
7637 // because of templates, which means that the previous
7638 // declaration is not necessarily from the class definition.
7639
7640 // For just setting the access, that doesn't matter.
7641 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7642 NewFD->setAccess(oldMethod->getAccess());
7643
7644 // Update the key-function state if necessary for this ABI.
7645 if (NewFD->isInlined() &&
7646 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7647 // setNonKeyFunction needs to work with the original
7648 // declaration from the class definition, and isVirtual() is
7649 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007650 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007651 if (oldMethod->isVirtual()) {
7652 Context.setNonKeyFunction(oldMethod);
7653 }
7654 }
7655 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007656 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007657 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007658
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007659 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007660 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007661 // C++-specific checks.
7662 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7663 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007664 } else if (CXXDestructorDecl *Destructor =
7665 dyn_cast<CXXDestructorDecl>(NewFD)) {
7666 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007667 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007668
Douglas Gregor7454c562010-07-02 20:37:36 +00007669 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007670 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007671 if (!ClassType->isDependentType()) {
7672 DeclarationName Name
7673 = Context.DeclarationNames.getCXXDestructorName(
7674 Context.getCanonicalType(ClassType));
7675 if (NewFD->getDeclName() != Name) {
7676 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007677 NewFD->setInvalidDecl();
7678 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007679 }
7680 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007681 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007682 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007683 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007684 }
7685
7686 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7688 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007689 !Method->getDescribedFunctionTemplate() &&
7690 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007691 if (AddOverriddenMethods(Method->getParent(), Method)) {
7692 // If the function was marked as "static", we have a problem.
7693 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007694 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007695 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007696 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007697 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007698
7699 if (Method->isStatic())
7700 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007701 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007702
7703 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7704 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007705 CheckOverloadedOperatorDeclaration(NewFD)) {
7706 NewFD->setInvalidDecl();
7707 return Redeclaration;
7708 }
Alexis Huntc88db062010-01-13 09:01:02 +00007709
7710 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7711 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007712 CheckLiteralOperatorDeclaration(NewFD)) {
7713 NewFD->setInvalidDecl();
7714 return Redeclaration;
7715 }
Alexis Huntc88db062010-01-13 09:01:02 +00007716
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007717 // In C++, check default arguments now that we have merged decls. Unless
7718 // the lexical context is the class, because in this case this is done
7719 // during delayed parsing anyway.
7720 if (!CurContext->isRecord())
7721 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007722
Douglas Gregor9246b682010-12-21 19:47:46 +00007723 // If this function declares a builtin function, check the type of this
7724 // declaration against the expected type for the builtin.
7725 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7726 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007727 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007728 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7729 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7730 // The type of this function differs from the type of the builtin,
7731 // so forget about the builtin entirely.
7732 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7733 }
7734 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007735
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007736 // If this function is declared as being extern "C", then check to see if
7737 // the function returns a UDT (class, struct, or union type) that is not C
7738 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007739 // But, issue any diagnostic on the first declaration only.
7740 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007741 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007742 if (R->isIncompleteType() && !R->isVoidType())
7743 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7744 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007745 else if (!R.isPODType(Context) && !R->isVoidType() &&
7746 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007747 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007748 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007749 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007750 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007751}
7752
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007753static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7754 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7755 if (!TSI)
7756 return SourceRange();
7757
7758 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007759 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007760 if (!FunctionTL)
7761 return SourceRange();
7762
Alp Toker42a16a62014-01-25 23:51:36 +00007763 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007764 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007765 return ResultTL.getSourceRange();
7766
7767 return SourceRange();
7768}
7769
David Blaikied937bf12011-09-08 06:33:04 +00007770void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007771 // C++11 [basic.start.main]p3:
7772 // A program that [...] declares main to be inline, static or
7773 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007774 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7775 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007776 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007777 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007778 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007779 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007780 ? diag::err_static_main : diag::warn_static_main)
7781 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7782 if (FD->isInlineSpecified())
7783 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7784 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007785 if (DS.isNoreturnSpecified()) {
7786 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7787 SourceRange NoreturnRange(NoreturnLoc,
7788 PP.getLocForEndOfToken(NoreturnLoc));
7789 Diag(NoreturnLoc, diag::ext_noreturn_main);
7790 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7791 << FixItHint::CreateRemoval(NoreturnRange);
7792 }
Richard Smith3f333f22012-02-04 06:10:17 +00007793 if (FD->isConstexpr()) {
7794 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7795 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7796 FD->setConstexpr(false);
7797 }
John McCall02dee0a2009-07-25 04:36:53 +00007798
Joey Goulya7310a82013-11-05 12:30:39 +00007799 if (getLangOpts().OpenCL) {
7800 Diag(FD->getLocation(), diag::err_opencl_no_main)
7801 << FD->hasAttr<OpenCLKernelAttr>();
7802 FD->setInvalidDecl();
7803 return;
7804 }
7805
John McCall02dee0a2009-07-25 04:36:53 +00007806 QualType T = FD->getType();
7807 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007808 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007809
John McCall5ed3caf2012-02-14 19:50:52 +00007810 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007811 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007812 // In C and C++, main magically returns 0 if you fall off the end;
7813 // set the flag which tells us that.
7814 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7815 FD->setHasImplicitReturnZero(true);
7816
7817 // In C with GNU extensions we allow main() to have non-integer return
7818 // type, but we should warn about the extension, and we disable the
7819 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007820 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007821 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7822
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007823 SourceRange ResultRange = getResultSourceRange(FD);
7824 if (ResultRange.isValid())
7825 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7826 << FixItHint::CreateReplacement(ResultRange, "int");
7827
John McCall5ed3caf2012-02-14 19:50:52 +00007828 // Otherwise, this is just a flat-out error.
7829 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007830 SourceRange ResultRange = getResultSourceRange(FD);
7831 if (ResultRange.isValid())
7832 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7833 << FixItHint::CreateReplacement(ResultRange, "int");
7834 else
7835 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7836
John McCall02dee0a2009-07-25 04:36:53 +00007837 FD->setInvalidDecl(true);
7838 }
7839
7840 // Treat protoless main() as nullary.
7841 if (isa<FunctionNoProtoType>(FT)) return;
7842
7843 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007844 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007845 assert(FD->getNumParams() == nparams);
7846
John McCall0e21fcc2009-12-24 09:58:38 +00007847 bool HasExtraParameters = (nparams > 3);
7848
7849 // Darwin passes an undocumented fourth argument of type char**. If
7850 // other platforms start sprouting these, the logic below will start
7851 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007852 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007853 HasExtraParameters = false;
7854
7855 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007856 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7857 FD->setInvalidDecl(true);
7858 nparams = 3;
7859 }
7860
7861 // FIXME: a lot of the following diagnostics would be improved
7862 // if we had some location information about types.
7863
7864 QualType CharPP =
7865 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007866 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007867
7868 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007869 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007870
7871 bool mismatch = true;
7872
7873 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7874 mismatch = false;
7875 else if (Expected[i] == CharPP) {
7876 // As an extension, the following forms are okay:
7877 // char const **
7878 // char const * const *
7879 // char * const *
7880
John McCall8ccfcb52009-09-24 19:53:00 +00007881 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007882 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007883 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7884 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007885 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7886 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007887 qs.removeConst();
7888 mismatch = !qs.empty();
7889 }
7890 }
7891
7892 if (mismatch) {
7893 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7894 // TODO: suggest replacing given type with expected type
7895 FD->setInvalidDecl(true);
7896 }
7897 }
7898
7899 if (nparams == 1 && !FD->isInvalidDecl()) {
7900 Diag(FD->getLocation(), diag::warn_main_one_arg);
7901 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007902
7903 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007904 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007905 FD->setInvalidDecl();
7906 }
7907}
7908
7909void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7910 QualType T = FD->getType();
7911 assert(T->isFunctionType() && "function decl is not of function type");
7912 const FunctionType *FT = T->castAs<FunctionType>();
7913
7914 // Set an implicit return of 'zero' if the function can return some integral,
7915 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007916 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7917 FT->getReturnType()->isAnyPointerType() ||
7918 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007919 // DllMain is exempt because a return value of zero means it failed.
7920 if (FD->getName() != "DllMain")
7921 FD->setHasImplicitReturnZero(true);
7922
7923 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007924 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007925 FD->setInvalidDecl();
7926 }
John McCalld9baf6a2009-07-24 03:03:21 +00007927}
7928
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007929bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007930 // FIXME: Need strict checking. In C89, we need to check for
7931 // any assignment, increment, decrement, function-calls, or
7932 // commas outside of a sizeof. In C99, it's the same list,
7933 // except that the aforementioned are allowed in unevaluated
7934 // expressions. Everything else falls under the
7935 // "may accept other forms of constant expressions" exception.
7936 // (We never end up here for C++, so the constant expression
7937 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007938 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007939 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007940 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7941 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007942 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007943}
7944
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007945namespace {
7946 // Visits an initialization expression to see if OrigDecl is evaluated in
7947 // its own initialization and throws a warning if it does.
7948 class SelfReferenceChecker
7949 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7950 Sema &S;
7951 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007952 bool isRecordType;
7953 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007954 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007955
7956 public:
7957 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7958
7959 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007960 S(S), OrigDecl(OrigDecl) {
7961 isPODType = false;
7962 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007963 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007964 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7965 isPODType = VD->getType().isPODType(S.Context);
7966 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007967 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007968 }
7969 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007970
Richard Trieu64c51ab2012-05-09 00:21:34 +00007971 // For most expressions, the cast is directly above the DeclRefExpr.
7972 // For conditional operators, the cast can be outside the conditional
7973 // operator if both expressions are DeclRefExpr's.
7974 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007975 if (isReferenceType)
7976 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007977 E = E->IgnoreParenImpCasts();
7978 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7979 HandleDeclRefExpr(DRE);
7980 return;
7981 }
7982
7983 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7984 HandleValue(CO->getTrueExpr());
7985 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007986 return;
7987 }
7988
7989 if (isa<MemberExpr>(E)) {
7990 Expr *Base = E->IgnoreParenImpCasts();
7991 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7992 // Check for static member variables and don't warn on them.
7993 if (!isa<FieldDecl>(ME->getMemberDecl()))
7994 return;
7995 Base = ME->getBase()->IgnoreParenImpCasts();
7996 }
7997 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7998 HandleDeclRefExpr(DRE);
7999 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008000 }
8001 }
8002
Richard Trieu32673472012-10-01 17:39:51 +00008003 // Reference types are handled here since all uses of references are
8004 // bad, not just r-value uses.
8005 void VisitDeclRefExpr(DeclRefExpr *E) {
8006 if (isReferenceType)
8007 HandleDeclRefExpr(E);
8008 }
8009
Richard Trieu64c51ab2012-05-09 00:21:34 +00008010 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00008011 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00008012 (isRecordType && E->getCastKind() == CK_NoOp))
8013 HandleValue(E->getSubExpr());
8014
8015 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008016 }
8017
Richard Trieua04ad1a2011-09-01 21:44:13 +00008018 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00008019 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00008020 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008021
Richard Trieu742c6ed2012-10-03 00:41:36 +00008022 // Warn when a non-static method call is followed by non-static member
8023 // field accesses, which is followed by a DeclRefExpr.
8024 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8025 bool Warn = (MD && !MD->isStatic());
8026 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8027 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8028 if (!isa<FieldDecl>(ME->getMemberDecl()))
8029 Warn = false;
8030 Base = ME->getBase()->IgnoreParenImpCasts();
8031 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008032
Richard Trieu742c6ed2012-10-03 00:41:36 +00008033 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8034 if (Warn)
8035 HandleDeclRefExpr(DRE);
8036 return;
8037 }
8038
8039 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8040 // Visit that expression.
8041 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008042 }
8043
Richard Trieu8fbd91d2013-03-26 03:41:40 +00008044 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8045 if (E->getNumArgs() > 0)
8046 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8047 HandleDeclRefExpr(DRE);
8048
8049 Inherited::VisitCXXOperatorCallExpr(E);
8050 }
8051
Richard Trieua04ad1a2011-09-01 21:44:13 +00008052 void VisitUnaryOperator(UnaryOperator *E) {
8053 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00008054 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8055 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8056 if (!isPODType)
8057 HandleValue(E->getSubExpr());
8058 return;
8059 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008060 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00008061 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008062
8063 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8064
Richard Trieua04ad1a2011-09-01 21:44:13 +00008065 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00008066 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008067 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00008068 unsigned diag;
8069 if (isReferenceType) {
8070 diag = diag::warn_uninit_self_reference_in_reference_init;
8071 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8072 diag = diag::warn_static_self_reference_in_init;
8073 } else {
8074 diag = diag::warn_uninit_self_reference_in_init;
8075 }
8076
Richard Trieua04ad1a2011-09-01 21:44:13 +00008077 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00008078 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00008079 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008080 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00008081 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008082 }
8083 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008084
Richard Trieu32673472012-10-01 17:39:51 +00008085 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8086 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8087 bool DirectInit) {
8088 // Parameters arguments are occassionially constructed with itself,
8089 // for instance, in recursive functions. Skip them.
8090 if (isa<ParmVarDecl>(OrigDecl))
8091 return;
8092
8093 E = E->IgnoreParens();
8094
8095 // Skip checking T a = a where T is not a record or reference type.
8096 // Doing so is a way to silence uninitialized warnings.
8097 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8098 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8099 if (ICE->getCastKind() == CK_LValueToRValue)
8100 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8101 if (DRE->getDecl() == OrigDecl)
8102 return;
8103
8104 SelfReferenceChecker(S, OrigDecl).Visit(E);
8105 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008106}
8107
Douglas Gregor5fb53972009-01-14 15:45:31 +00008108/// AddInitializerToDecl - Adds the initializer Init to the
8109/// declaration dcl. If DirectInit is true, this is C++ direct
8110/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008111void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8112 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008113 // If there is no declaration, there was an error parsing it. Just ignore
8114 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008115 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008116 return;
Mike Stump11289f42009-09-09 15:08:12 +00008117
Douglas Gregor0c880302009-03-11 23:00:04 +00008118 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8119 // With declarators parsed the way they are, the parser cannot
8120 // distinguish between a normal initializer and a pure-specifier.
8121 // Thus this grotesque test.
8122 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008123 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008124 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8125 CheckPureMethod(Method, Init->getSourceRange());
8126 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008127 Diag(Method->getLocation(), diag::err_member_function_initialization)
8128 << Method->getDeclName() << Init->getSourceRange();
8129 Method->setInvalidDecl();
8130 }
8131 return;
8132 }
8133
Steve Naroff437b4d82007-09-12 20:13:48 +00008134 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8135 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008136 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8137 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008138 RealDecl->setInvalidDecl();
8139 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008140 }
Sebastian Redla9351792012-02-11 23:51:47 +00008141 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8142
Richard Smith0cc85782011-12-15 19:20:59 +00008143 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008144 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008145 Expr *DeduceInit = Init;
8146 // Initializer could be a C++ direct-initializer. Deduction only works if it
8147 // contains exactly one expression.
8148 if (CXXDirectInit) {
8149 if (CXXDirectInit->getNumExprs() == 0) {
8150 // It isn't possible to write this directly, but it is possible to
8151 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008152 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008153 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8154 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008155 << VDecl->getDeclName() << VDecl->getType()
8156 << VDecl->getSourceRange();
8157 RealDecl->setInvalidDecl();
8158 return;
8159 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008160 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008161 VDecl->isInitCapture()
8162 ? diag::err_init_capture_multiple_expressions
8163 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008164 << VDecl->getDeclName() << VDecl->getType()
8165 << VDecl->getSourceRange();
8166 RealDecl->setInvalidDecl();
8167 return;
8168 } else {
8169 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008170 if (isa<InitListExpr>(DeduceInit))
8171 Diag(CXXDirectInit->getLocStart(),
8172 diag::err_auto_var_init_paren_braces)
8173 << VDecl->getDeclName() << VDecl->getType()
8174 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008175 }
8176 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008177
8178 // Expressions default to 'id' when we're in a debugger.
8179 bool DefaultedToAuto = false;
8180 if (getLangOpts().DebuggerCastResultToId &&
8181 Init->getType() == Context.UnknownAnyTy) {
8182 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8183 if (Result.isInvalid()) {
8184 VDecl->setInvalidDecl();
8185 return;
8186 }
8187 Init = Result.take();
8188 DefaultedToAuto = true;
8189 }
Richard Smith061f1e22013-04-30 21:23:01 +00008190
8191 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008192 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008193 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008194 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008195 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008196 RealDecl->setInvalidDecl();
8197 return;
8198 }
Richard Smith061f1e22013-04-30 21:23:01 +00008199 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008200 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008201
John McCall31168b02011-06-15 23:02:42 +00008202 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008203 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008204 VDecl->setInvalidDecl();
8205
Jordan Rosed8d56692012-06-08 22:46:07 +00008206 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8207 // 'id' instead of a specific object type prevents most of our usual checks.
8208 // We only want to warn outside of template instantiations, though:
8209 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008210 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008211 DeducedType->isObjCIdType()) {
8212 SourceLocation Loc =
8213 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008214 Diag(Loc, diag::warn_auto_var_is_id)
8215 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8216 }
8217
Richard Smith30482bc2011-02-20 03:19:35 +00008218 // If this is a redeclaration, check that the type we just deduced matches
8219 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008220 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8221 // We never need to merge the type, because we cannot form an incomplete
8222 // array of auto, nor deduce such a type.
8223 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8224 }
Richard Smith27d807c2013-04-30 13:56:41 +00008225
8226 // Check the deduced type is valid for a variable declaration.
8227 CheckVariableDeclarationType(VDecl);
8228 if (VDecl->isInvalidDecl())
8229 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008230 }
Richard Smith0cc85782011-12-15 19:20:59 +00008231
Nico Rieck8e9791f2014-02-26 21:27:13 +00008232 // dllimport cannot be used on variable definitions.
8233 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8234 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8235 VDecl->setInvalidDecl();
8236 return;
8237 }
8238
Richard Smith0cc85782011-12-15 19:20:59 +00008239 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8240 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8241 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8242 VDecl->setInvalidDecl();
8243 return;
8244 }
8245
Sebastian Redla9351792012-02-11 23:51:47 +00008246 if (!VDecl->getType()->isDependentType()) {
8247 // A definition must end up with a complete type, which means it must be
8248 // complete with the restriction that an array type might be completed by
8249 // the initializer; note that later code assumes this restriction.
8250 QualType BaseDeclType = VDecl->getType();
8251 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8252 BaseDeclType = Array->getElementType();
8253 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8254 diag::err_typecheck_decl_incomplete_type)) {
8255 RealDecl->setInvalidDecl();
8256 return;
8257 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008258
Sebastian Redla9351792012-02-11 23:51:47 +00008259 // The variable can not have an abstract class type.
8260 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8261 diag::err_abstract_type_in_decl,
8262 AbstractVariableType))
8263 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008264 }
8265
Sebastian Redl5ca79842010-02-01 20:16:42 +00008266 const VarDecl *Def;
8267 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008268 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008269 << VDecl->getDeclName();
8270 Diag(Def->getLocation(), diag::note_previous_definition);
8271 VDecl->setInvalidDecl();
8272 return;
8273 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008274
Douglas Gregorf0f83692010-08-24 05:27:49 +00008275 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008276 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008277 // C++ [class.static.data]p4
8278 // If a static data member is of const integral or const
8279 // enumeration type, its declaration in the class definition can
8280 // specify a constant-initializer which shall be an integral
8281 // constant expression (5.19). In that case, the member can appear
8282 // in integral constant expressions. The member shall still be
8283 // defined in a namespace scope if it is used in the program and the
8284 // namespace scope definition shall not contain an initializer.
8285 //
8286 // We already performed a redefinition check above, but for static
8287 // data members we also need to check whether there was an in-class
8288 // declaration with an initializer.
8289 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008290 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8291 << VDecl->getDeclName();
8292 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008293 return;
8294 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008295
Douglas Gregor71f39c92010-12-16 01:31:22 +00008296 if (VDecl->hasLocalStorage())
8297 getCurFunction()->setHasBranchProtectedScope();
8298
8299 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8300 VDecl->setInvalidDecl();
8301 return;
8302 }
8303 }
John McCalld4e1b762010-08-01 01:24:59 +00008304
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008305 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8306 // a kernel function cannot be initialized."
8307 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8308 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8309 VDecl->setInvalidDecl();
8310 return;
8311 }
8312
Steve Naroff61091402007-09-12 14:07:44 +00008313 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008314 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008315 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008316
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008317 // Expressions default to 'id' when we're in a debugger
8318 // and we are assigning it to a variable of Objective-C pointer type.
8319 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8320 Init->getType() == Context.UnknownAnyTy) {
8321 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8322 if (Result.isInvalid()) {
8323 VDecl->setInvalidDecl();
8324 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008325 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008326 Init = Result.take();
8327 }
Richard Smith0cc85782011-12-15 19:20:59 +00008328
8329 // Perform the initialization.
8330 if (!VDecl->isInvalidDecl()) {
8331 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8332 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008333 = DirectInit ?
8334 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8335 Init->getLocStart(),
8336 Init->getLocEnd())
8337 : InitializationKind::CreateDirectList(
8338 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008339 : InitializationKind::CreateCopy(VDecl->getLocation(),
8340 Init->getLocStart());
8341
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008342 MultiExprArg Args = Init;
8343 if (CXXDirectInit)
8344 Args = MultiExprArg(CXXDirectInit->getExprs(),
8345 CXXDirectInit->getNumExprs());
8346
8347 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8348 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008349 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008350 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008351 return;
Steve Naroff61091402007-09-12 14:07:44 +00008352 }
Richard Smith0cc85782011-12-15 19:20:59 +00008353
8354 Init = Result.takeAs<Expr>();
8355 }
8356
Richard Trieu32673472012-10-01 17:39:51 +00008357 // Check for self-references within variable initializers.
8358 // Variables declared within a function/method body (except for references)
8359 // are handled by a dataflow analysis.
8360 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8361 VDecl->getType()->isReferenceType()) {
8362 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8363 }
8364
Richard Smith0cc85782011-12-15 19:20:59 +00008365 // If the type changed, it means we had an incomplete type that was
8366 // completed by the initializer. For example:
8367 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008368 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008369 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008370 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008371
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008372 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008373 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8374
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008375 if (VDecl->hasAttr<BlocksAttr>())
8376 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008377
8378 // It is safe to assign a weak reference into a strong variable.
8379 // Although this code can still have problems:
8380 // id x = self.weakProp;
8381 // id y = self.weakProp;
8382 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8383 // paths through the function. This should be revisited if
8384 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008385 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008386 DiagnosticsEngine::Level Level =
8387 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8388 Init->getLocStart());
8389 if (Level != DiagnosticsEngine::Ignored)
8390 getCurFunction()->markSafeWeakUse(Init);
8391 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008392 }
8393
Richard Smith945f8d32013-01-14 22:39:08 +00008394 // The initialization is usually a full-expression.
8395 //
8396 // FIXME: If this is a braced initialization of an aggregate, it is not
8397 // an expression, and each individual field initializer is a separate
8398 // full-expression. For instance, in:
8399 //
8400 // struct Temp { ~Temp(); };
8401 // struct S { S(Temp); };
8402 // struct T { S a, b; } t = { Temp(), Temp() }
8403 //
8404 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008405 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8406 false,
8407 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008408 if (Result.isInvalid()) {
8409 VDecl->setInvalidDecl();
8410 return;
8411 }
8412 Init = Result.take();
8413
Richard Smith0cc85782011-12-15 19:20:59 +00008414 // Attach the initializer to the decl.
8415 VDecl->setInit(Init);
8416
8417 if (VDecl->isLocalVarDecl()) {
8418 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8419 // static storage duration shall be constant expressions or string literals.
8420 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008421 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8422 if (VDecl->getStorageClass() == SC_Static)
8423 CheckForConstantInitializer(Init, DclT);
8424 // C89 is stricter than C99 for non-static aggregate types.
8425 // C89 6.5.7p3: All the expressions [...] in an initializer list
8426 // for an object that has aggregate or union type shall be
8427 // constant expressions.
8428 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008429 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008430 !Init->isConstantInitializer(Context, false))
8431 Diag(Init->getExprLoc(),
8432 diag::ext_aggregate_init_not_constant)
8433 << Init->getSourceRange();
8434 }
Mike Stump11289f42009-09-09 15:08:12 +00008435 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008436 VDecl->getLexicalDeclContext()->isRecord()) {
8437 // This is an in-class initialization for a static data member, e.g.,
8438 //
8439 // struct S {
8440 // static const int value = 17;
8441 // };
8442
Douglas Gregor0c880302009-03-11 23:00:04 +00008443 // C++ [class.mem]p4:
8444 // A member-declarator can contain a constant-initializer only
8445 // if it declares a static member (9.4) of const integral or
8446 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008447 //
Richard Smith0cc85782011-12-15 19:20:59 +00008448 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008449 // If a non-volatile const static data member is of integral or
8450 // enumeration type, its declaration in the class definition can
8451 // specify a brace-or-equal-initializer in which every initalizer-clause
8452 // that is an assignment-expression is a constant expression. A static
8453 // data member of literal type can be declared in the class definition
8454 // with the constexpr specifier; if so, its declaration shall specify a
8455 // brace-or-equal-initializer in which every initializer-clause that is
8456 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008457
8458 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008459 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008460
Richard Smith2316cd82011-09-29 19:11:37 +00008461 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008462 // type. We separately check that every constexpr variable is of literal
8463 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008464 } else if (VDecl->isConstexpr()) {
8465
John McCalldb768922010-09-10 23:21:22 +00008466 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008467 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008468 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8469 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008470 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008471
8472 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008473 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008474 // Check whether the expression is a constant expression.
8475 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008476 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008477 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008478 // in-class initializer cannot be volatile.
8479 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8480 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008481 ; // Nothing to check.
8482 else if (Init->isIntegerConstantExpr(Context, &Loc))
8483 ; // Ok, it's an ICE!
8484 else if (Init->isEvaluatable(Context)) {
8485 // If we can constant fold the initializer through heroics, accept it,
8486 // but report this as a use of an extension for -pedantic.
8487 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8488 << Init->getSourceRange();
8489 } else {
8490 // Otherwise, this is some crazy unknown case. Report the issue at the
8491 // location provided by the isIntegerConstantExpr failed check.
8492 Diag(Loc, diag::err_in_class_initializer_non_constant)
8493 << Init->getSourceRange();
8494 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008495 }
8496
Richard Smith0cc85782011-12-15 19:20:59 +00008497 // We allow foldable floating-point constants as an extension.
8498 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008499 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8500 // it anyway and provide a fixit to add the 'constexpr'.
8501 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008502 Diag(VDecl->getLocation(),
8503 diag::ext_in_class_initializer_float_type_cxx11)
8504 << DclT << Init->getSourceRange();
8505 Diag(VDecl->getLocStart(),
8506 diag::note_in_class_initializer_float_type_cxx11)
8507 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008508 } else {
8509 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8510 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008511
Richard Smithcf656382013-01-25 04:22:16 +00008512 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8513 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8514 << Init->getSourceRange();
8515 VDecl->setInvalidDecl();
8516 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008517 }
Richard Smith256336d2011-09-29 23:18:34 +00008518
Richard Smith0cc85782011-12-15 19:20:59 +00008519 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008520 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008521 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008522 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008523 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8524 VDecl->setConstexpr(true);
8525
Richard Smith2316cd82011-09-29 19:11:37 +00008526 } else {
8527 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008528 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008529 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008530 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008531 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008532 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008533 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008534 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008535 VDecl->isExternC())) &&
8536 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008537 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008538
Richard Smith0cc85782011-12-15 19:20:59 +00008539 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008540 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008541 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008542 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8543 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8544 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008545 !Init->isConstantInitializer(
8546 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008547 // GNU C++98 edits for __thread, [basic.start.init]p4:
8548 // An object of thread storage duration shall not require dynamic
8549 // initialization.
8550 // FIXME: Need strict checking here.
8551 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8552 if (getLangOpts().CPlusPlus11)
8553 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8554 }
Steve Naroff61091402007-09-12 14:07:44 +00008555 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008556
Sebastian Redla9351792012-02-11 23:51:47 +00008557 // We will represent direct-initialization similarly to copy-initialization:
8558 // int x(1); -as-> int x = 1;
8559 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8560 //
8561 // Clients that want to distinguish between the two forms, can check for
8562 // direct initializer using VarDecl::getInitStyle().
8563 // A major benefit is that clients that don't particularly care about which
8564 // exactly form was it (like the CodeGen) can handle both cases without
8565 // special case code.
8566
8567 // C++ 8.5p11:
8568 // The form of initialization (using parentheses or '=') is generally
8569 // insignificant, but does matter when the entity being initialized has a
8570 // class type.
8571 if (CXXDirectInit) {
8572 assert(DirectInit && "Call-style initializer must be direct init.");
8573 VDecl->setInitStyle(VarDecl::CallInit);
8574 } else if (DirectInit) {
8575 // This must be list-initialization. No other way is direct-initialization.
8576 VDecl->setInitStyle(VarDecl::ListInit);
8577 }
8578
John McCall8b7fd8f12011-01-19 11:48:09 +00008579 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008580}
8581
John McCalleae5acb2010-03-31 02:13:20 +00008582/// ActOnInitializerError - Given that there was an error parsing an
8583/// initializer for the given declaration, try to return to some form
8584/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008585void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008586 // Our main concern here is re-establishing invariants like "a
8587 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008588 if (!D || D->isInvalidDecl()) return;
8589
8590 VarDecl *VD = dyn_cast<VarDecl>(D);
8591 if (!VD) return;
8592
Richard Smith30482bc2011-02-20 03:19:35 +00008593 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008594 if (ParsingInitForAutoVars.count(D)) {
8595 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008596 return;
8597 }
8598
John McCalleae5acb2010-03-31 02:13:20 +00008599 QualType Ty = VD->getType();
8600 if (Ty->isDependentType()) return;
8601
8602 // Require a complete type.
8603 if (RequireCompleteType(VD->getLocation(),
8604 Context.getBaseElementType(Ty),
8605 diag::err_typecheck_decl_incomplete_type)) {
8606 VD->setInvalidDecl();
8607 return;
8608 }
8609
Alp Toker48c7e172014-04-15 16:24:50 +00008610 // Require a non-abstract type.
John McCalleae5acb2010-03-31 02:13:20 +00008611 if (RequireNonAbstractType(VD->getLocation(), Ty,
8612 diag::err_abstract_type_in_decl,
8613 AbstractVariableType)) {
8614 VD->setInvalidDecl();
8615 return;
8616 }
8617
8618 // Don't bother complaining about constructors or destructors,
8619 // though.
8620}
8621
John McCall48871652010-08-21 09:40:31 +00008622void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008623 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008624 // If there is no declaration, there was an error parsing it. Just ignore it.
8625 if (RealDecl == 0)
8626 return;
8627
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008628 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8629 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008630
Richard Smithf0215fe2011-12-25 21:17:58 +00008631 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008632 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008633 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8634 << Var->getDeclName() << Type;
8635 Var->setInvalidDecl();
8636 return;
8637 }
Mike Stump11289f42009-09-09 15:08:12 +00008638
Richard Smithf0215fe2011-12-25 21:17:58 +00008639 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008640 // the constexpr specifier; if so, its declaration shall specify
8641 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008642 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8643 // the definition of a variable [...] or the declaration of a static data
8644 // member.
8645 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8646 if (Var->isStaticDataMember())
8647 Diag(Var->getLocation(),
8648 diag::err_constexpr_static_mem_var_requires_init)
8649 << Var->getDeclName();
8650 else
8651 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008652 Var->setInvalidDecl();
8653 return;
8654 }
8655
Joey Gouly96b94e62014-01-03 14:16:55 +00008656 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8657 // be initialized.
8658 if (!Var->isInvalidDecl() &&
8659 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008660 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008661 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8662 Var->setInvalidDecl();
8663 return;
8664 }
8665
Douglas Gregore6565622010-02-09 07:26:29 +00008666 switch (Var->isThisDeclarationADefinition()) {
8667 case VarDecl::Definition:
8668 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8669 break;
8670
8671 // We have an out-of-line definition of a static data member
8672 // that has an in-class initializer, so we type-check this like
8673 // a declaration.
8674 //
8675 // Fall through
8676
8677 case VarDecl::DeclarationOnly:
8678 // It's only a declaration.
8679
8680 // Block scope. C99 6.7p7: If an identifier for an object is
8681 // declared with no linkage (C99 6.2.2p6), the type for the
8682 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008683 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008684 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008685 RequireCompleteType(Var->getLocation(), Type,
8686 diag::err_typecheck_decl_incomplete_type))
8687 Var->setInvalidDecl();
8688
8689 // Make sure that the type is not abstract.
8690 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8691 RequireNonAbstractType(Var->getLocation(), Type,
8692 diag::err_abstract_type_in_decl,
8693 AbstractVariableType))
8694 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008695 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008696 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008697 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008698 Diag(Var->getLocation(), diag::note_private_extern);
8699 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008700
Douglas Gregore6565622010-02-09 07:26:29 +00008701 return;
8702
8703 case VarDecl::TentativeDefinition:
8704 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8705 // object that has file scope without an initializer, and without a
8706 // storage-class specifier or with the storage-class specifier "static",
8707 // constitutes a tentative definition. Note: A tentative definition with
8708 // external linkage is valid (C99 6.2.2p5).
8709 if (!Var->isInvalidDecl()) {
8710 if (const IncompleteArrayType *ArrayT
8711 = Context.getAsIncompleteArrayType(Type)) {
8712 if (RequireCompleteType(Var->getLocation(),
8713 ArrayT->getElementType(),
8714 diag::err_illegal_decl_array_incomplete_type))
8715 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008716 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008717 // C99 6.9.2p3: If the declaration of an identifier for an object is
8718 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8719 // declared type shall not be an incomplete type.
8720 // NOTE: code such as the following
8721 // static struct s;
8722 // struct s { int a; };
8723 // is accepted by gcc. Hence here we issue a warning instead of
8724 // an error and we do not invalidate the static declaration.
8725 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008726 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008727 RequireCompleteType(Var->getLocation(), Type,
8728 diag::ext_typecheck_decl_incomplete_type);
8729 }
8730 }
8731
8732 // Record the tentative definition; we're done.
8733 if (!Var->isInvalidDecl())
8734 TentativeDefinitions.push_back(Var);
8735 return;
8736 }
8737
8738 // Provide a specific diagnostic for uninitialized variable
8739 // definitions with incomplete array type.
8740 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008741 Diag(Var->getLocation(),
8742 diag::err_typecheck_incomplete_array_needs_initializer);
8743 Var->setInvalidDecl();
8744 return;
8745 }
8746
John McCalla755f0f2010-08-01 01:25:24 +00008747 // Provide a specific diagnostic for uninitialized variable
8748 // definitions with reference type.
8749 if (Type->isReferenceType()) {
8750 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8751 << Var->getDeclName()
8752 << SourceRange(Var->getLocation(), Var->getLocation());
8753 Var->setInvalidDecl();
8754 return;
8755 }
Douglas Gregore6565622010-02-09 07:26:29 +00008756
8757 // Do not attempt to type-check the default initializer for a
8758 // variable with dependent type.
8759 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008760 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008761
Douglas Gregore6565622010-02-09 07:26:29 +00008762 if (Var->isInvalidDecl())
8763 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008764
Douglas Gregore6565622010-02-09 07:26:29 +00008765 if (RequireCompleteType(Var->getLocation(),
8766 Context.getBaseElementType(Type),
8767 diag::err_typecheck_decl_incomplete_type)) {
8768 Var->setInvalidDecl();
8769 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008770 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008771
Douglas Gregore6565622010-02-09 07:26:29 +00008772 // The variable can not have an abstract class type.
8773 if (RequireNonAbstractType(Var->getLocation(), Type,
8774 diag::err_abstract_type_in_decl,
8775 AbstractVariableType)) {
8776 Var->setInvalidDecl();
8777 return;
8778 }
8779
Douglas Gregor9574af62011-05-21 17:52:48 +00008780 // Check for jumps past the implicit initializer. C++0x
8781 // clarifies that this applies to a "variable with automatic
8782 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008783 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008784 // A program that jumps from a point where a variable with automatic
8785 // storage duration is not in scope to a point where it is in scope is
8786 // ill-formed unless the variable has scalar type, class type with a
8787 // trivial default constructor and a trivial destructor, a cv-qualified
8788 // version of one of these types, or an array of one of the preceding
8789 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008790 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008791 if (const RecordType *Record
8792 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008793 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008794 // Mark the function for further checking even if the looser rules of
8795 // C++11 do not require such checks, so that we can diagnose
8796 // incompatibilities with C++98.
8797 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008798 getCurFunction()->setHasBranchProtectedScope();
8799 }
Douglas Gregore6565622010-02-09 07:26:29 +00008800 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008801
8802 // C++03 [dcl.init]p9:
8803 // If no initializer is specified for an object, and the
8804 // object is of (possibly cv-qualified) non-POD class type (or
8805 // array thereof), the object shall be default-initialized; if
8806 // the object is of const-qualified type, the underlying class
8807 // type shall have a user-declared default
8808 // constructor. Otherwise, if no initializer is specified for
8809 // a non- static object, the object and its subobjects, if
8810 // any, have an indeterminate initial value); if the object
8811 // or any of its subobjects are of const-qualified type, the
8812 // program is ill-formed.
8813 // C++0x [dcl.init]p11:
8814 // If no initializer is specified for an object, the object is
8815 // default-initialized; [...].
8816 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8817 InitializationKind Kind
8818 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008819
8820 InitializationSequence InitSeq(*this, Entity, Kind, None);
8821 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008822 if (Init.isInvalid())
8823 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008824 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008825 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008826 // This is important for template substitution.
8827 Var->setInitStyle(VarDecl::CallInit);
8828 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008829
John McCall8b7fd8f12011-01-19 11:48:09 +00008830 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008831 }
8832}
8833
Richard Smith02e85f32011-04-14 22:09:26 +00008834void Sema::ActOnCXXForRangeDecl(Decl *D) {
8835 VarDecl *VD = dyn_cast<VarDecl>(D);
8836 if (!VD) {
8837 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8838 D->setInvalidDecl();
8839 return;
8840 }
8841
8842 VD->setCXXForRangeDecl(true);
8843
8844 // for-range-declaration cannot be given a storage class specifier.
8845 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008846 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008847 case SC_None:
8848 break;
8849 case SC_Extern:
8850 Error = 0;
8851 break;
8852 case SC_Static:
8853 Error = 1;
8854 break;
8855 case SC_PrivateExtern:
8856 Error = 2;
8857 break;
8858 case SC_Auto:
8859 Error = 3;
8860 break;
8861 case SC_Register:
8862 Error = 4;
8863 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008864 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008865 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008866 }
Richard Smith2316cd82011-09-29 19:11:37 +00008867 if (VD->isConstexpr())
8868 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008869 if (Error != -1) {
8870 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8871 << VD->getDeclName() << Error;
8872 D->setInvalidDecl();
8873 }
8874}
8875
John McCall8b7fd8f12011-01-19 11:48:09 +00008876void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8877 if (var->isInvalidDecl()) return;
8878
John McCall31168b02011-06-15 23:02:42 +00008879 // In ARC, don't allow jumps past the implicit initialization of a
8880 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008881 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008882 var->hasLocalStorage()) {
8883 switch (var->getType().getObjCLifetime()) {
8884 case Qualifiers::OCL_None:
8885 case Qualifiers::OCL_ExplicitNone:
8886 case Qualifiers::OCL_Autoreleasing:
8887 break;
8888
8889 case Qualifiers::OCL_Weak:
8890 case Qualifiers::OCL_Strong:
8891 getCurFunction()->setHasBranchProtectedScope();
8892 break;
8893 }
8894 }
8895
John McCall8a4e2e42014-01-29 08:33:09 +00008896 // Warn about externally-visible variables being defined without a
8897 // prior declaration. We only want to do this for global
8898 // declarations, but we also specifically need to avoid doing it for
8899 // class members because the linkage of an anonymous class can
8900 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008901 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008902 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008903 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008904 getDiagnostics().getDiagnosticLevel(
8905 diag::warn_missing_variable_declarations,
8906 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008907 // Find a previous declaration that's not a definition.
8908 VarDecl *prev = var->getPreviousDecl();
8909 while (prev && prev->isThisDeclarationADefinition())
8910 prev = prev->getPreviousDecl();
8911
8912 if (!prev)
8913 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8914 }
8915
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008916 if (var->getTLSKind() == VarDecl::TLS_Static &&
8917 var->getType().isDestructedType()) {
8918 // GNU C++98 edits for __thread, [basic.start.term]p3:
8919 // The type of an object with thread storage duration shall not
8920 // have a non-trivial destructor.
8921 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8922 if (getLangOpts().CPlusPlus11)
8923 Diag(var->getLocation(), diag::note_use_thread_local);
8924 }
8925
Warren Huntc3b18962014-04-08 22:30:47 +00008926 if (var->isThisDeclarationADefinition() &&
8927 ActiveTemplateInstantiations.empty()) {
8928 PragmaStack<StringLiteral *> *Stack = nullptr;
8929 int SectionFlags = PSF_Implicit | PSF_Read;
8930 if (var->getType().isConstQualified())
8931 Stack = &ConstSegStack;
8932 else if (!var->getInit()) {
8933 Stack = &BSSSegStack;
8934 SectionFlags |= PSF_Write;
8935 } else {
8936 Stack = &DataSegStack;
8937 SectionFlags |= PSF_Write;
8938 }
8939 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
8940 var->addAttr(
8941 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8942 Stack->CurrentValue->getString(),
8943 Stack->CurrentPragmaLocation));
8944 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
8945 if (UnifySection(SA->getName(), SectionFlags, var))
8946 var->dropAttr<SectionAttr>();
8947 }
8948
John McCall8b7fd8f12011-01-19 11:48:09 +00008949 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008950 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008951
Richard Smithde63d362012-11-09 23:03:14 +00008952 QualType type = var->getType();
8953 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008954
8955 // __block variables might require us to capture a copy-initializer.
8956 if (var->hasAttr<BlocksAttr>()) {
8957 // It's currently invalid to ever have a __block variable with an
8958 // array type; should we diagnose that here?
8959
8960 // Regardless, we don't want to ignore array nesting when
8961 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008962 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008963 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008964 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008965 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008966 ExprResult result
8967 = PerformMoveOrCopyInitialization(
8968 InitializedEntity::InitializeBlock(poi, type, false),
8969 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008970 if (!result.isInvalid()) {
8971 result = MaybeCreateExprWithCleanups(result);
8972 Expr *init = result.takeAs<Expr>();
8973 Context.setBlockVarCopyInits(var, init);
8974 }
8975 }
8976 }
8977
Richard Smitheda3c842011-11-07 22:16:17 +00008978 Expr *Init = var->getInit();
8979 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008980 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008981
Richard Smithbf830092012-10-29 18:26:47 +00008982 if (!var->getDeclContext()->isDependentContext() &&
8983 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008984 if (IsGlobal && !var->isConstexpr() &&
8985 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8986 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008987 != DiagnosticsEngine::Ignored) {
8988 // Warn about globals which don't have a constant initializer. Don't
8989 // warn about globals with a non-trivial destructor because we already
8990 // warned about them.
8991 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8992 if (!(RD && !RD->hasTrivialDestructor()) &&
8993 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8994 Diag(var->getLocation(), diag::warn_global_constructor)
8995 << Init->getSourceRange();
8996 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008997
Richard Smithd0b4dd62011-12-19 06:19:21 +00008998 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008999 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00009000 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9001 SourceLocation DiagLoc = var->getLocation();
9002 // If the note doesn't add any useful information other than a source
9003 // location, fold it into the primary diagnostic.
9004 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9005 diag::note_invalid_subexpr_in_const_expr) {
9006 DiagLoc = Notes[0].first;
9007 Notes.clear();
9008 }
9009 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9010 << var << Init->getSourceRange();
9011 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9012 Diag(Notes[I].first, Notes[I].second);
9013 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00009014 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009015 // Check whether the initializer of a const variable of integral or
9016 // enumeration type is an ICE now, since we can't tell whether it was
9017 // initialized by a constant expression if we check later.
9018 var->checkInitIsICE();
9019 }
Richard Smitheda3c842011-11-07 22:16:17 +00009020 }
John McCall8b7fd8f12011-01-19 11:48:09 +00009021
9022 // Require the destructor.
9023 if (const RecordType *recordType = baseType->getAs<RecordType>())
9024 FinalizeVarWithDestructor(var, recordType);
9025}
9026
Richard Smithb2bc2e62011-02-21 20:05:19 +00009027/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9028/// any semantic actions necessary after any initializer has been attached.
9029void
9030Sema::FinalizeDeclaration(Decl *ThisDecl) {
9031 // Note that we are no longer parsing the initializer for this declaration.
9032 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009033
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009034 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00009035 if (!VD)
9036 return;
9037
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00009038 checkAttributesAfterMerging(*this, *VD);
9039
Rafael Espindola87198cd2013-08-16 23:18:50 +00009040 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9041 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00009042 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00009043 VD->dropAttr<UsedAttr>();
9044 }
9045 }
9046
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009047 if (!VD->isInvalidDecl() &&
9048 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9049 if (const VarDecl *Def = VD->getDefinition()) {
9050 if (Def->hasAttr<AliasAttr>()) {
9051 Diag(VD->getLocation(), diag::err_tentative_after_alias)
9052 << VD->getDeclName();
9053 Diag(Def->getLocation(), diag::note_previous_definition);
9054 VD->setInvalidDecl();
9055 }
9056 }
9057 }
9058
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009059 const DeclContext *DC = VD->getDeclContext();
9060 // If there's a #pragma GCC visibility in scope, and this isn't a class
9061 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00009062 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009063 AddPushedVisibilityAttribute(VD);
9064
Richard Smithc3926172014-04-02 18:28:36 +00009065 // FIXME: Warn on unused templates.
Richard Smith6c6ef822014-04-25 19:21:40 +00009066 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9067 !isa<VarTemplatePartialSpecializationDecl>(VD))
Rafael Espindolad2ecc132013-01-03 04:29:20 +00009068 MarkUnusedFileScopedDecl(VD);
9069
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009070 // Now we have parsed the initializer and can update the table of magic
9071 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00009072 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9073 !VD->getType()->isIntegralOrEnumerationType())
9074 return;
9075
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00009076 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00009077 const Expr *MagicValueExpr = VD->getInit();
9078 if (!MagicValueExpr) {
9079 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009080 }
Rafael Espindola60470f12013-01-03 04:05:19 +00009081 llvm::APSInt MagicValueInt;
9082 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9083 Diag(I->getRange().getBegin(),
9084 diag::err_type_tag_for_datatype_not_ice)
9085 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9086 continue;
9087 }
9088 if (MagicValueInt.getActiveBits() > 64) {
9089 Diag(I->getRange().getBegin(),
9090 diag::err_type_tag_for_datatype_too_large)
9091 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9092 continue;
9093 }
9094 uint64_t MagicValue = MagicValueInt.getZExtValue();
9095 RegisterTypeTagForDatatype(I->getArgumentKind(),
9096 MagicValue,
9097 I->getMatchingCType(),
9098 I->getLayoutCompatible(),
9099 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009100 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00009101}
9102
Rafael Espindolaab417692013-07-09 12:05:01 +00009103Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9104 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009105 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009106
9107 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00009108 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009109
David Majnemer50ce8352013-09-17 23:57:10 +00009110 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009111 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00009112 if (Decl *D = Group[i]) {
9113 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9114 if (!FirstDeclaratorInGroup)
9115 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00009116 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00009117 }
Richard Smith2abf6762011-02-23 00:37:57 +00009118
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009119 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009120 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00009121 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00009122 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9123 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9124 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009125 }
David Blaikie095deba2012-11-14 01:52:05 +00009126
Rafael Espindolaab417692013-07-09 12:05:01 +00009127 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009128}
9129
9130/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9131/// group, performing any necessary semantic checking.
9132Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00009133Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009134 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009135 // C++0x [dcl.spec.auto]p7:
9136 // If the type deduced for the template parameter U is not the same in each
9137 // deduction, the program is ill-formed.
9138 // FIXME: When initializer-list support is added, a distinction is needed
9139 // between the deduced type U and the deduced type which 'auto' stands for.
9140 // auto a = 0, b = { 1, 2, 3 };
9141 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009142 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009143 QualType Deduced;
9144 CanQualType DeducedCanon;
9145 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009146 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009147 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9148 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009149 // Don't reissue diagnostics when instantiating a template.
9150 if (AT && D->isInvalidDecl())
9151 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009152 QualType U = AT ? AT->getDeducedType() : QualType();
9153 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009154 CanQualType UCanon = Context.getCanonicalType(U);
9155 if (Deduced.isNull()) {
9156 Deduced = U;
9157 DeducedCanon = UCanon;
9158 DeducedDecl = D;
9159 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009160 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9161 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009162 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009163 << Deduced << DeducedDecl->getDeclName()
9164 << U << D->getDeclName()
9165 << DeducedDecl->getInit()->getSourceRange()
9166 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009167 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009168 break;
9169 }
9170 }
9171 }
9172 }
9173 }
9174
Rafael Espindolaab417692013-07-09 12:05:01 +00009175 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009176
Rafael Espindolaab417692013-07-09 12:05:01 +00009177 return DeclGroupPtrTy::make(
9178 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009179}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009180
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009181void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009182 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009183}
9184
Rafael Espindolaab417692013-07-09 12:05:01 +00009185void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009186 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009187 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009188 return;
9189
9190 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9191 Group[0]->getLocation())
9192 == DiagnosticsEngine::Ignored)
9193 return;
9194
Rafael Espindolaab417692013-07-09 12:05:01 +00009195 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009196 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009197 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009198 // additional declaration references:
9199 // 'typedef struct S {} S;'
9200 // 'typedef struct S *S;'
9201 // 'struct S *pS;'
9202 // FinalizeDeclaratorGroup adds these as separate declarations.
9203 Decl *MaybeTagDecl = Group[0];
9204 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009205 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009206 }
9207 }
9208
9209 // See if there are any new comments that are not attached to a decl.
9210 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9211 if (!Comments.empty() &&
9212 !Comments.back()->isAttached()) {
9213 // There is at least one comment that not attached to a decl.
9214 // Maybe it should be attached to one of these decls?
9215 //
9216 // Note that this way we pick up not only comments that precede the
9217 // declaration, but also comments that *follow* the declaration -- thanks to
9218 // the lookahead in the lexer: we've consumed the semicolon and looked
9219 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009220 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009221 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009222 }
9223}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009224
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009225/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9226/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009227Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009228 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009229
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009230 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009231
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009232 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009233 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009234 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009235 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009236 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009237 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9238 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009239 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009240 Diag(DS.getStorageClassSpecLoc(),
9241 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009242 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009243 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009244
Richard Smithb4a9e862013-04-12 22:46:28 +00009245 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9246 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9247 << DeclSpec::getSpecifierName(TSCS);
9248 if (DS.isConstexprSpecified())
9249 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009250 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009251
Richard Smithb4a9e862013-04-12 22:46:28 +00009252 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009253
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009254 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009255 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009256
David Blaikiebbafb8a2012-03-11 07:00:24 +00009257 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009258 // Check that there are no default arguments inside the type of this
9259 // parameter.
9260 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009261
9262 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9263 if (D.getCXXScopeSpec().isSet()) {
9264 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9265 << D.getCXXScopeSpec().getRange();
9266 D.getCXXScopeSpec().clear();
9267 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009268 }
9269
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009270 // Ensure we have a valid name
9271 IdentifierInfo *II = 0;
9272 if (D.hasName()) {
9273 II = D.getIdentifier();
9274 if (!II) {
9275 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009276 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009277 D.setInvalidType(true);
9278 }
9279 }
9280
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009281 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009282 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009283 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9284 ForRedeclaration);
9285 LookupName(R, S);
9286 if (R.isSingleResult()) {
9287 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009288 if (PrevDecl->isTemplateParameter()) {
9289 // Maybe we will complain about the shadowed template parameter.
9290 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9291 // Just pretend that we didn't see the previous declaration.
9292 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009293 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009294 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009295 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009296
Chris Lattnerd9773512009-01-21 02:38:50 +00009297 // Recover by removing the name
9298 II = 0;
9299 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009300 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009301 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009302 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009303 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009304
John McCallf7b2fb52010-01-22 00:28:27 +00009305 // Temporarily put parameter variables in the translation unit, not
9306 // the enclosing context. This prevents them from accidentally
9307 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009308 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009309 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009310 D.getIdentifierLoc(), II,
9311 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009312 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009313
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009314 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009315 New->setInvalidDecl();
9316
9317 assert(S->isFunctionPrototypeScope());
9318 assert(S->getFunctionPrototypeDepth() >= 1);
9319 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9320 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009321
Douglas Gregor91f84212008-12-11 16:49:14 +00009322 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009323 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009324 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009325 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009326
Douglas Gregor758a8692009-06-17 21:51:59 +00009327 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009328
Douglas Gregor41866812011-09-12 18:37:38 +00009329 if (D.getDeclSpec().isModulePrivateSpecified())
9330 Diag(New->getLocation(), diag::err_module_private_local)
9331 << 1 << New->getDeclName()
9332 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9333 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9334
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009335 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009336 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9337 }
John McCall48871652010-08-21 09:40:31 +00009338 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009339}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009340
John McCalla3ccba02010-06-04 11:21:44 +00009341/// \brief Synthesizes a variable for a parameter arising from a
9342/// typedef.
9343ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9344 SourceLocation Loc,
9345 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009346 /* FIXME: setting StartLoc == Loc.
9347 Would it be worth to modify callers so as to provide proper source
9348 location for the unnamed parameters, embedding the parameter's type? */
9349 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009350 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009351 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009352 Param->setImplicit();
9353 return Param;
9354}
9355
John McCallc5990642010-08-24 09:05:15 +00009356void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9357 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009358 // Don't diagnose unused-parameter errors in template instantiations; we
9359 // will already have done so in the template itself.
9360 if (!ActiveTemplateInstantiations.empty())
9361 return;
9362
9363 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009364 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009365 !(*Param)->hasAttr<UnusedAttr>()) {
9366 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9367 << (*Param)->getDeclName();
9368 }
9369 }
9370}
9371
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009372void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9373 ParmVarDecl * const *ParamEnd,
9374 QualType ReturnTy,
9375 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009376 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009377 return;
9378
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009379 // Warn if the return value is pass-by-value and larger than the specified
9380 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009381 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009382 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009383 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009384 Diag(D->getLocation(), diag::warn_return_value_size)
9385 << D->getDeclName() << Size;
9386 }
9387
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009388 // Warn if any parameter is pass-by-value and larger than the specified
9389 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009390 for (; Param != ParamEnd; ++Param) {
9391 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009392 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009393 continue;
9394 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009395 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009396 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9397 << (*Param)->getDeclName() << Size;
9398 }
9399}
9400
Abramo Bagnaradff19302011-03-08 08:55:46 +00009401ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9402 SourceLocation NameLoc, IdentifierInfo *Name,
9403 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009404 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009405 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009406 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009407 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009408 T->isObjCLifetimeType()) {
9409
9410 Qualifiers::ObjCLifetime lifetime;
9411
9412 // Special cases for arrays:
9413 // - if it's const, use __unsafe_unretained
9414 // - otherwise, it's an error
9415 if (T->isArrayType()) {
9416 if (!T.isConstQualified()) {
9417 DelayedDiagnostics.add(
9418 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009419 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009420 }
9421 lifetime = Qualifiers::OCL_ExplicitNone;
9422 } else {
9423 lifetime = T->getObjCARCImplicitLifetime();
9424 }
9425 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009426 }
9427
Abramo Bagnaradff19302011-03-08 08:55:46 +00009428 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009429 Context.getAdjustedParameterType(T),
9430 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009431 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009432
9433 // Parameters can not be abstract class types.
9434 // For record types, this is done by the AbstractClassUsageDiagnoser once
9435 // the class has been completely parsed.
9436 if (!CurContext->isRecord() &&
9437 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9438 AbstractParamType))
9439 New->setInvalidDecl();
9440
9441 // Parameter declarators cannot be interface types. All ObjC objects are
9442 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009443 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009444 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009445 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009446 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009447 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009448 T = Context.getObjCObjectPointerType(T);
9449 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009450 }
9451
9452 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9453 // duration shall not be qualified by an address-space qualifier."
9454 // Since all parameters have automatic store duration, they can not have
9455 // an address space.
9456 if (T.getAddressSpace() != 0) {
Fraser Cormack01648e02014-04-15 11:38:29 +00009457 // OpenCL allows function arguments declared to be an array of a type
9458 // to be qualified with an address space.
9459 if (!(getLangOpts().OpenCL && T->isArrayType())) {
9460 Diag(NameLoc, diag::err_arg_with_address_space);
9461 New->setInvalidDecl();
9462 }
Douglas Gregor940bca72010-04-12 07:48:19 +00009463 }
9464
9465 return New;
9466}
9467
Douglas Gregor170512f2009-04-01 23:51:29 +00009468void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9469 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009470 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009471
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009472 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9473 // for a K&R function.
9474 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009475 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009476 --i;
Alp Tokerc5350722014-02-26 22:27:52 +00009477 if (FTI.Params[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009478 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009479 llvm::raw_svector_ostream(Code)
9480 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9481 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9482 << FTI.Params[i].Ident
9483 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009484
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009485 // Implicitly declare the argument as type 'int' for lack of a better
9486 // type.
John McCall084e83d2011-03-24 11:26:52 +00009487 AttributeFactory attrs;
9488 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009489 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009490 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009491 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9492 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009493 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009494 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9495 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009496 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009497 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9498 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009499 }
9500 }
Mike Stump11289f42009-09-09 15:08:12 +00009501 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009502}
9503
Richard Smith79a52e52012-04-17 22:30:01 +00009504Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009505 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009506 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009507 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009508
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009509 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009510 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009511 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009512}
9513
Anders Carlsson2a45e402012-12-18 01:29:20 +00009514static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9515 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009516 // Don't warn about invalid declarations.
9517 if (FD->isInvalidDecl())
9518 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009519
Anders Carlsson31c7e882009-12-09 03:30:09 +00009520 // Or declarations that aren't global.
9521 if (!FD->isGlobal())
9522 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009523
Anders Carlsson31c7e882009-12-09 03:30:09 +00009524 // Don't warn about C++ member functions.
9525 if (isa<CXXMethodDecl>(FD))
9526 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009527
Anders Carlsson31c7e882009-12-09 03:30:09 +00009528 // Don't warn about 'main'.
9529 if (FD->isMain())
9530 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009531
Anders Carlsson31c7e882009-12-09 03:30:09 +00009532 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009533 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009534 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009535
9536 // Don't warn about function templates.
9537 if (FD->getDescribedFunctionTemplate())
9538 return false;
9539
9540 // Don't warn about function template specializations.
9541 if (FD->isFunctionTemplateSpecialization())
9542 return false;
9543
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009544 // Don't warn for OpenCL kernels.
9545 if (FD->hasAttr<OpenCLKernelAttr>())
9546 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009547
Anders Carlsson31c7e882009-12-09 03:30:09 +00009548 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009549 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9550 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009551 // Ignore any declarations that occur in function or method
9552 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009553 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009554 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009555
Anders Carlsson31c7e882009-12-09 03:30:09 +00009556 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009557 if (FD->getNumParams() == 0)
9558 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009559 break;
9560 }
Richard Smith541b38b2013-09-20 01:15:31 +00009561
Anders Carlsson31c7e882009-12-09 03:30:09 +00009562 return MissingPrototype;
9563}
9564
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009565void
9566Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9567 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009568 // Don't complain if we're in GNU89 mode and the previous definition
9569 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009570 const FunctionDecl *Definition = EffectiveDefinition;
9571 if (!Definition)
9572 if (!FD->isDefined(Definition))
9573 return;
9574
9575 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009576 return;
9577
9578 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9579 Definition->getStorageClass() == SC_Extern)
9580 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009581 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009582 else
9583 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9584
9585 Diag(Definition->getLocation(), diag::note_previous_definition);
9586 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009587}
Faisal Valia17d19f2013-11-07 05:17:06 +00009588
9589
Faisal Valic1a6dc42013-10-23 16:10:50 +00009590static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9591 Sema &S) {
9592 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009593
9594 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009595 LSI->CallOperator = CallOperator;
9596 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009597 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009598 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9599
9600 if (LCD == LCD_None)
9601 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9602 else if (LCD == LCD_ByCopy)
9603 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9604 else if (LCD == LCD_ByRef)
9605 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9606 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9607
9608 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9609 LSI->Mutable = !CallOperator->isConst();
9610
Faisal Valia17d19f2013-11-07 05:17:06 +00009611 // Add the captures to the LSI so they can be noted as already
9612 // captured within tryCaptureVar.
Aaron Ballman6def98a2014-03-13 17:08:33 +00009613 for (const auto &C : LambdaClass->captures()) {
9614 if (C.capturesVariable()) {
9615 VarDecl *VD = C.getCapturedVar();
Faisal Valia17d19f2013-11-07 05:17:06 +00009616 if (VD->isInitCapture())
9617 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9618 QualType CaptureType = VD->getType();
Aaron Ballman6def98a2014-03-13 17:08:33 +00009619 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
Faisal Valia17d19f2013-11-07 05:17:06 +00009620 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
Aaron Ballman6def98a2014-03-13 17:08:33 +00009621 /*RefersToEnclosingLocal*/true, C.getLocation(),
9622 /*EllipsisLoc*/C.isPackExpansion()
9623 ? C.getEllipsisLoc() : SourceLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +00009624 CaptureType, /*Expr*/ 0);
9625
Aaron Ballman6def98a2014-03-13 17:08:33 +00009626 } else if (C.capturesThis()) {
9627 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +00009628 S.getCurrentThisType(), /*Expr*/ 0);
9629 }
9630 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009631}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009632
John McCall48871652010-08-21 09:40:31 +00009633Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009634 // Clear the last template instantiation error context.
9635 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9636
Douglas Gregor17a7c122009-06-24 00:54:41 +00009637 if (!D)
9638 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009639 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009640
John McCall48871652010-08-21 09:40:31 +00009641 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009642 FD = FunTmpl->getTemplatedDecl();
9643 else
John McCall48871652010-08-21 09:40:31 +00009644 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009645 // If we are instantiating a generic lambda call operator, push
9646 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009647 // that's already been calculated (ActOnLambdaExpr) to prime the current
9648 // LambdaScopeInfo.
9649 // When the template operator is being specialized, the LambdaScopeInfo,
9650 // has to be properly restored so that tryCaptureVariable doesn't try
9651 // and capture any new variables. In addition when calculating potential
9652 // captures during transformation of nested lambdas, it is necessary to
9653 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009654 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009655 assert(ActiveTemplateInstantiations.size() &&
9656 "There should be an active template instantiation on the stack "
9657 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009658 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009659 }
9660 else
9661 // Enter a new function scope
9662 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009663
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009664 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009665 if (!FD->isLateTemplateParsed())
9666 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009667
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009668 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009669 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009670 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9671 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009672 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009673 FD->setInvalidDecl();
9674 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009675 }
9676
Eli Friedman9ad72442009-03-04 07:30:59 +00009677 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009678 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009679 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009680 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009681 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009682 RequireCompleteType(FD->getLocation(), ResultType,
9683 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009684 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009685
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009686 // GNU warning -Wmissing-prototypes:
9687 // Warn if a global function is defined without a previous
9688 // prototype declaration. This warning is issued even if the
9689 // definition itself provides a prototype. The aim is to detect
9690 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009691 const FunctionDecl *PossibleZeroParamPrototype = 0;
9692 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009693 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009694
Anders Carlsson2a45e402012-12-18 01:29:20 +00009695 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009696 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009697 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009698 if (TypeSourceInfo *TI =
9699 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9700 TypeLoc TL = TI->getTypeLoc();
9701 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9702 Diag(PossibleZeroParamPrototype->getLocation(),
9703 diag::note_declaration_not_a_prototype)
9704 << PossibleZeroParamPrototype
9705 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9706 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009707 }
9708 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009709
Douglas Gregor67da0d92009-05-15 17:59:04 +00009710 if (FnBodyScope)
9711 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009712
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009713 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009714 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9715 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009716
9717 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00009718 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +00009719 Param->setOwningFunction(FD);
9720
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009721 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009722 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009723 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009724
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009725 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009726 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009727 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009728
James Molloy6f8780b2012-02-29 10:24:19 +00009729 // If we had any tags defined in the function prototype,
9730 // introduce them into the function scope.
9731 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009732 for (ArrayRef<NamedDecl *>::iterator
9733 I = FD->getDeclsInPrototypeScope().begin(),
9734 E = FD->getDeclsInPrototypeScope().end();
9735 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009736 NamedDecl *D = *I;
9737
9738 // Some of these decls (like enums) may have been pinned to the translation unit
9739 // for lack of a real context earlier. If so, remove from the translation unit
9740 // and reattach to the current context.
9741 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9742 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +00009743 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9744 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +00009745 Context.getTranslationUnitDecl()->removeDecl(D);
9746 break;
9747 }
9748 }
9749 // Either way, reassign the lexical decl context to our FunctionDecl.
9750 D->setLexicalDeclContext(CurContext);
9751 }
9752
9753 // If the decl has a non-null name, make accessible in the current scope.
9754 if (!D->getName().empty())
9755 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9756
9757 // Similarly, dive into enums and fish their constants out, making them
9758 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00009759 if (auto *ED = dyn_cast<EnumDecl>(D)) {
9760 for (auto *EI : ED->enumerators())
9761 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009762 }
9763 }
9764 }
9765
Richard Smith79a52e52012-04-17 22:30:01 +00009766 // Ensure that the function's exception specification is instantiated.
9767 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9768 ResolveExceptionSpec(D->getLocation(), FPT);
9769
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009770 // Checking attributes of current function definition
9771 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009772 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009773 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009774 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009775 // Microsoft accepts dllimport for functions defined within class scope.
9776 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009777 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009778 Diag(FD->getLocation(),
9779 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009780 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009781 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009782 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009783 }
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009784 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009785 // We want to attach documentation to original Decl (which might be
9786 // a function template).
9787 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009788 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009789}
9790
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009791/// \brief Given the set of return statements within a function body,
9792/// compute the variables that are subject to the named return value
9793/// optimization.
9794///
9795/// Each of the variables that is subject to the named return value
9796/// optimization will be marked as NRVO variables in the AST, and any
9797/// return statement that has a marked NRVO variable as its NRVO candidate can
9798/// use the named return value optimization.
9799///
9800/// This function applies a very simplistic algorithm for NRVO: if every return
9801/// statement in the function has the same NRVO candidate, that candidate is
9802/// the NRVO variable.
9803///
9804/// FIXME: Employ a smarter algorithm that accounts for multiple return
9805/// statements and the lifetimes of the NRVO candidates. We should be able to
9806/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009807void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009808 ReturnStmt **Returns = Scope->Returns.data();
9809
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009810 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009811 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009812 if (!Returns[I]->getNRVOCandidate())
9813 return;
9814
9815 if (!NRVOCandidate)
9816 NRVOCandidate = Returns[I]->getNRVOCandidate();
9817 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9818 return;
9819 }
9820
9821 if (NRVOCandidate)
9822 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9823}
9824
Richard Smith8e6002f2014-03-12 23:14:33 +00009825bool Sema::canDelayFunctionBody(const Declarator &D) {
9826 // We can't delay parsing the body of a constexpr function template (yet).
9827 if (D.getDeclSpec().isConstexprSpecified())
9828 return false;
9829
9830 // We can't delay parsing the body of a function template with a deduced
9831 // return type (yet).
9832 if (D.getDeclSpec().containsPlaceholderType()) {
9833 // If the placeholder introduces a non-deduced trailing return type,
9834 // we can still delay parsing it.
9835 if (D.getNumTypeObjects()) {
9836 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9837 if (Outer.Kind == DeclaratorChunk::Function &&
9838 Outer.Fun.hasTrailingReturnType()) {
9839 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9840 return Ty.isNull() || !Ty->isUndeducedType();
9841 }
9842 }
9843 return false;
9844 }
9845
9846 return true;
9847}
9848
Richard Smith1ab34b32012-11-19 21:13:18 +00009849bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009850 // We cannot skip the body of a function (or function template) which is
9851 // constexpr, since we may need to evaluate its body in order to parse the
9852 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009853 // We cannot skip the body of a function with an undeduced return type,
9854 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009855 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009856 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009857 return false;
9858 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009859}
9860
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009861Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009862 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009863 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009864 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009865 MD->setHasSkippedBody();
9866 return ActOnFinishFunctionBody(Decl, 0);
9867}
9868
John McCallfaf5fb42010-08-26 23:41:50 +00009869Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009870 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009871}
9872
John McCallb268a282010-08-23 23:25:46 +00009873Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9874 bool IsInstantiation) {
Alp Tokera2794f92014-01-22 07:29:52 +00009875 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009876
Ted Kremenek0b405322010-03-23 00:13:23 +00009877 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009878 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009879
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009880 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009881 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009882
Richard Smith7500ab22013-05-10 04:31:10 +00009883 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009884 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009885 // If the function has a deduced result type but contains no 'return'
9886 // statements, the result type as written must be exactly 'auto', and
9887 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009888 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009889 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009890 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009891 FD->setInvalidDecl();
9892 } else {
9893 // Substitute 'void' for the 'auto' in the type.
9894 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009895 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009896 Context.adjustDeducedFunctionResultType(
9897 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009898 }
9899 }
9900
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009901 // The only way to be included in UndefinedButUsed is if there is an
9902 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009903 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009904 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009905 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009906 UndefinedButUsed.erase(FD);
9907 else if (FD->isInlined() &&
9908 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9909 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9910 UndefinedButUsed.erase(FD);
9911 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009912
John McCall5ed3caf2012-02-14 19:50:52 +00009913 // If the function implicitly returns zero (like 'main') or is naked,
9914 // don't complain about missing return statements.
9915 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009916 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009917
Francois Pichet3abc9b82011-05-11 02:14:46 +00009918 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009919 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009920 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009921 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9922
Douglas Gregor88d292c2010-05-13 16:44:06 +00009923 if (!FD->isInvalidDecl()) {
Reid Kleckner121b1a12014-04-30 16:31:28 +00009924 // Don't diagnose unused parameters of defaulted or deleted functions.
9925 if (Body)
9926 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009927 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009928 FD->getReturnType(), FD);
9929
Douglas Gregor88d292c2010-05-13 16:44:06 +00009930 // If this is a constructor, we need a vtable.
9931 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9932 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009933
Jordan Rosed39e5f12012-07-02 21:19:23 +00009934 // Try to apply the named return value optimization. We have to check
9935 // if we can do this here because lambdas keep return statements around
9936 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +00009937 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +00009938 !FD->isDependentContext())
9939 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009940 }
9941
Douglas Gregor21f46922012-02-08 20:17:14 +00009942 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9943 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009944 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009945 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009946 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009947 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009948 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009949 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009950 MD->getReturnType(), MD);
9951
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009952 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009953 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009954 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009955 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009956 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9957 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009958 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009959 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009960 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9961 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009962 bool isDesignated =
9963 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009964 assert(isDesignated && InitMethod);
9965 (void)isDesignated;
Argyrios Kyrtzidisde103662014-04-16 18:32:51 +00009966
9967 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
9968 auto IFace = MD->getClassInterface();
9969 if (!IFace)
9970 return false;
9971 auto SuperD = IFace->getSuperClass();
9972 if (!SuperD)
9973 return false;
9974 return SuperD->getIdentifier() ==
9975 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
9976 };
9977 // Don't issue this warning for unavailable inits or direct subclasses
9978 // of NSObject.
9979 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +00009980 Diag(MD->getLocation(),
9981 diag::warn_objc_designated_init_missing_super_call);
9982 Diag(InitMethod->getLocation(),
9983 diag::note_objc_designated_init_marked_here);
9984 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009985 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9986 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009987 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +00009988 // Don't issue this warning for unavaialable inits.
9989 if (!MD->isUnavailable())
9990 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009991 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9992 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009993 } else {
John McCall48871652010-08-21 09:40:31 +00009994 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009995 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009996
Jordan Rose2afd6612012-10-19 16:05:26 +00009997 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009998 "This should only be set for ObjC methods, which should have been "
9999 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +000010000
Chris Lattnere2473062007-05-28 06:28:18 +000010001 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +000010002 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000010003 // C++ constructors that have function-try-blocks can't have return
10004 // statements in the handlers of that block. (C++ [except.handle]p14)
10005 // Verify this.
10006 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10007 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10008
Richard Smithdef8bdb2011-08-12 18:44:32 +000010009 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +000010010 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +000010011 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000010012 !hasAnyUnrecoverableErrorsInThisFunction() &&
10013 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +000010014 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +000010015
John McCalldeb646e2010-08-04 01:04:25 +000010016 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10017 if (!Destructor->getParent()->isDependentType())
10018 CheckDestructor(Destructor);
10019
John McCalla6309952010-03-16 21:39:52 +000010020 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10021 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +000010022 }
Douglas Gregor9a28e842010-03-01 23:15:13 +000010023
10024 // If any errors have occurred, clear out any temporaries that may have
10025 // been leftover. This ensures that these temporaries won't be picked up for
10026 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +000010027 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +000010028 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +000010029 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010030 }
10031 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
10032 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +000010033 // Since the body is valid, issue any analysis-based warnings that are
10034 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +000010035 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +000010036 }
10037
Richard Smith3607ffe2012-02-13 03:54:03 +000010038 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10039 (!CheckConstexprFunctionDecl(FD) ||
10040 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +000010041 FD->setInvalidDecl();
10042
John McCall28fc7092011-11-10 05:35:25 +000010043 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +000010044 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +000010045 assert(MaybeODRUseExprs.empty() &&
10046 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +000010047 }
10048
John McCalle99d5f32010-03-25 22:08:03 +000010049 if (!IsInstantiation)
10050 PopDeclContext();
10051
Eli Friedman71c80552012-01-05 03:35:19 +000010052 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +000010053 // If any errors have occurred, clear out any temporaries that may have
10054 // been leftover. This ensures that these temporaries won't be picked up for
10055 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +000010056 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +000010057 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +000010058 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +000010059
John McCall48871652010-08-21 09:40:31 +000010060 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +000010061}
10062
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010063
10064/// When we finish delayed parsing of an attribute, we must attach it to the
10065/// relevant Decl.
10066void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10067 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000010068 // Always attach attributes to the underlying decl.
10069 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10070 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +000010071 ProcessDeclAttributeList(S, D, Attrs.getList());
10072
10073 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10074 if (Method->isStatic())
10075 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010076}
10077
10078
Chris Lattnerac18be92006-11-20 06:49:47 +000010079/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10080/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +000010081NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +000010082 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010083 // Before we produce a declaration for an implicitly defined
10084 // function, see whether there was a locally-scoped declaration of
10085 // this name as a function or variable. If so, use that
10086 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +000010087 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10088 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10089 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10090 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010091 }
10092
Chris Lattner00e26072008-05-05 21:18:06 +000010093 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +000010094 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +000010095 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +000010096 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010097 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +000010098 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +000010099 else
Hans Wennborg70a13242011-12-08 15:56:07 +000010100 diag_id = diag::warn_implicit_function_decl;
10101 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +000010102
Hans Wennborg70a13242011-12-08 15:56:07 +000010103 // Because typo correction is expensive, only do it if the implicit
10104 // function declaration is going to be treated as an error.
10105 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10106 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000010107 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +000010108 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
John Thompson2255f2c2014-04-23 12:57:01 +000010109 LookupOrdinaryName, S, 0, Validator,
10110 CTK_NonError)))
Richard Smithf9b15102013-08-17 00:46:16 +000010111 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10112 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +000010113 }
10114
Chris Lattnerac18be92006-11-20 06:49:47 +000010115 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +000010116 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +000010117 AttributeFactory attrFactory;
10118 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +000010119 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +000010120 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10121 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010122 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +000010123 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010124 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +000010125 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010126 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10127 /*IsAmbiguous=*/false,
Richard Smith151b8a32014-04-07 15:16:58 +000010128 /*LParenLoc=*/NoLoc,
10129 /*Params=*/0,
10130 /*NumParams=*/0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010131 /*EllipsisLoc=*/NoLoc,
10132 /*RParenLoc=*/NoLoc,
10133 /*TypeQuals=*/0,
10134 /*RefQualifierIsLvalueRef=*/true,
10135 /*RefQualifierLoc=*/NoLoc,
10136 /*ConstQualifierLoc=*/NoLoc,
10137 /*VolatileQualifierLoc=*/NoLoc,
10138 /*MutableLoc=*/NoLoc,
10139 EST_None,
10140 /*ESpecLoc=*/NoLoc,
10141 /*Exceptions=*/0,
10142 /*ExceptionRanges=*/0,
10143 /*NumExceptions=*/0,
10144 /*NoexceptExpr=*/0,
10145 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +000010146 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010147 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010148 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010149
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010150 // Insert this function into translation-unit scope.
10151
10152 DeclContext *PrevDC = CurContext;
10153 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010154
Jordan Rosed03d99d2013-03-05 01:27:54 +000010155 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010156 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010157
10158 CurContext = PrevDC;
10159
Douglas Gregore711f702009-02-14 18:57:46 +000010160 AddKnownFunctionAttributes(FD);
10161
Steve Naroff3913ea42008-04-04 14:32:09 +000010162 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010163}
10164
Douglas Gregore711f702009-02-14 18:57:46 +000010165/// \brief Adds any function attributes that we know a priori based on
10166/// the declaration of this function.
10167///
10168/// These attributes can apply both to implicitly-declared builtins
10169/// (like __builtin___printf_chk) or to library-declared functions
10170/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010171///
10172/// We need to check for duplicate attributes both here and where user-written
10173/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010174void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10175 if (FD->isInvalidDecl())
10176 return;
10177
10178 // If this is a built-in function, map its builtin attributes to
10179 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010180 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010181 // Handle printf-formatting attributes.
10182 unsigned FormatIdx;
10183 bool HasVAListArg;
10184 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010185 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010186 const char *fmt = "printf";
10187 unsigned int NumParams = FD->getNumParams();
10188 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10189 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10190 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010191 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010192 &Context.Idents.get(fmt),
10193 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010194 HasVAListArg ? 0 : FormatIdx+2,
10195 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010196 }
Douglas Gregore711f702009-02-14 18:57:46 +000010197 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010198 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10199 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010200 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010201 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010202 &Context.Idents.get("scanf"),
10203 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010204 HasVAListArg ? 0 : FormatIdx+2,
10205 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010206 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010207
10208 // Mark const if we don't care about errno and that is the only
10209 // thing preventing the function from being const. This allows
10210 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010211 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010212 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010213 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010214 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010215 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010216
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010217 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010218 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010219 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10220 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010221 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010222 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010223 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010224 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010225 }
10226
10227 IdentifierInfo *Name = FD->getIdentifier();
10228 if (!Name)
10229 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010230 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010231 FD->getDeclContext()->isTranslationUnit()) ||
10232 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010233 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010234 LinkageSpecDecl::lang_c)) {
10235 // Okay: this could be a libc/libm/Objective-C function we know
10236 // about.
10237 } else
10238 return;
10239
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010240 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010241 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010242 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010243 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010244 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010245 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010246 Name->isStr("vasprintf") ? 0 : 3,
10247 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010248 }
Jordan Rose742c6072012-08-08 21:17:31 +000010249
10250 if (Name->isStr("__CFStringMakeConstantString")) {
10251 // We already have a __builtin___CFStringMakeConstantString,
10252 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010253 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010254 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10255 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010256 }
Douglas Gregore711f702009-02-14 18:57:46 +000010257}
Chris Lattner302b4be2006-11-19 02:31:38 +000010258
John McCall703a3f82009-10-24 08:00:42 +000010259TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010260 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010261 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010262 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010263
John McCallbcd03502009-12-07 02:54:59 +000010264 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010265 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010266 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010267 }
10268
Chris Lattner18b19622007-01-22 07:39:13 +000010269 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010270 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010271 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010272 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010273 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010274 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010275
John McCall04fcd0d2011-02-01 08:20:08 +000010276 // Bail out immediately if we have an invalid declaration.
10277 if (D.isInvalidType()) {
10278 NewTD->setInvalidDecl();
10279 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010280 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010281
Douglas Gregor41866812011-09-12 18:37:38 +000010282 if (D.getDeclSpec().isModulePrivateSpecified()) {
10283 if (CurContext->isFunctionOrMethod())
10284 Diag(NewTD->getLocation(), diag::err_module_private_local)
10285 << 2 << NewTD->getDeclName()
10286 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10287 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10288 else
10289 NewTD->setModulePrivate();
10290 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010291
John McCall04fcd0d2011-02-01 08:20:08 +000010292 // C++ [dcl.typedef]p8:
10293 // If the typedef declaration defines an unnamed class (or
10294 // enum), the first typedef-name declared by the declaration
10295 // to be that class type (or enum type) is used to denote the
10296 // class type (or enum type) for linkage purposes only.
10297 // We need to check whether the type was declared in the declaration.
10298 switch (D.getDeclSpec().getTypeSpecType()) {
10299 case TST_enum:
10300 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010301 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010302 case TST_union:
10303 case TST_class: {
10304 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10305
10306 // Do nothing if the tag is not anonymous or already has an
10307 // associated typedef (from an earlier typedef in this decl group).
10308 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010309 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010310
10311 // A well-formed anonymous tag must always be a TUK_Definition.
10312 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10313
10314 // The type must match the tag exactly; no qualifiers allowed.
10315 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10316 break;
10317
John McCall2575d882014-01-30 01:12:53 +000010318 // If we've already computed linkage for the anonymous tag, then
10319 // adding a typedef name for the anonymous decl can change that
10320 // linkage, which might be a serious problem. Diagnose this as
10321 // unsupported and ignore the typedef name. TODO: we should
10322 // pursue this as a language defect and establish a formal rule
10323 // for how to handle it.
10324 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10325 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10326
10327 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10328 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10329 getLangOpts());
10330
10331 llvm::SmallString<40> textToInsert;
10332 textToInsert += ' ';
10333 textToInsert += D.getIdentifier()->getName();
10334 Diag(tagLoc, diag::note_typedef_changes_linkage)
10335 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10336 break;
10337 }
10338
John McCall04fcd0d2011-02-01 08:20:08 +000010339 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010340 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010341 break;
10342 }
10343
10344 default:
10345 break;
10346 }
10347
Steve Narofff93b6722007-08-28 20:14:24 +000010348 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010349}
10350
Douglas Gregord9034f02009-05-14 16:41:31 +000010351
Richard Smith4b38ded2012-03-14 23:13:10 +000010352/// \brief Check that this is a valid underlying type for an enum declaration.
10353bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10354 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10355 QualType T = TI->getType();
10356
Eli Friedman52f32b92012-12-18 02:37:32 +000010357 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010358 return false;
10359
Eli Friedman52f32b92012-12-18 02:37:32 +000010360 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10361 if (BT->isInteger())
10362 return false;
10363
Richard Smith4b38ded2012-03-14 23:13:10 +000010364 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10365 return true;
10366}
10367
10368/// Check whether this is a valid redeclaration of a previous enumeration.
10369/// \return true if the redeclaration was invalid.
10370bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10371 QualType EnumUnderlyingTy,
10372 const EnumDecl *Prev) {
10373 bool IsFixed = !EnumUnderlyingTy.isNull();
10374
10375 if (IsScoped != Prev->isScoped()) {
10376 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10377 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010378 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010379 return true;
10380 }
10381
10382 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010383 if (!EnumUnderlyingTy->isDependentType() &&
10384 !Prev->getIntegerType()->isDependentType() &&
10385 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010386 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010387 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010388 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10389 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010390 Diag(Prev->getLocation(), diag::note_previous_declaration)
10391 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010392 return true;
10393 }
10394 } else if (IsFixed != Prev->isFixed()) {
10395 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10396 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010397 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010398 return true;
10399 }
10400
10401 return false;
10402}
10403
Joao Matosdc86f942012-08-31 18:45:21 +000010404/// \brief Get diagnostic %select index for tag kind for
10405/// redeclaration diagnostic message.
10406/// WARNING: Indexes apply to particular diagnostics only!
10407///
10408/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010409static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010410 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010411 case TTK_Struct: return 0;
10412 case TTK_Interface: return 1;
10413 case TTK_Class: return 2;
10414 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010415 }
Joao Matosdc86f942012-08-31 18:45:21 +000010416}
10417
10418/// \brief Determine if tag kind is a class-key compatible with
10419/// class for redeclaration (class, struct, or __interface).
10420///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010421/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010422static bool isClassCompatTagKind(TagTypeKind Tag)
10423{
10424 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10425}
10426
Douglas Gregord9034f02009-05-14 16:41:31 +000010427/// \brief Determine whether a tag with a given kind is acceptable
10428/// as a redeclaration of the given tag declaration.
10429///
10430/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010431bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010432 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010433 SourceLocation NewTagLoc,
10434 const IdentifierInfo &Name) {
10435 // C++ [dcl.type.elab]p3:
10436 // The class-key or enum keyword present in the
10437 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010438 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010439 // refers. This rule also applies to the form of
10440 // elaborated-type-specifier that declares a class-name or
10441 // friend class since it can be construed as referring to the
10442 // definition of the class. Thus, in any
10443 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010444 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010445 // used to refer to a union (clause 9), and either the class or
10446 // struct class-key shall be used to refer to a class (clause 9)
10447 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010448 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010449 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010450 if (OldTag == NewTag)
10451 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010452
Joao Matosdc86f942012-08-31 18:45:21 +000010453 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010454 // Warn about the struct/class tag mismatch.
10455 bool isTemplate = false;
10456 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10457 isTemplate = Record->getDescribedClassTemplate();
10458
Richard Trieucaa33d32011-06-10 03:11:26 +000010459 if (!ActiveTemplateInstantiations.empty()) {
10460 // In a template instantiation, do not offer fix-its for tag mismatches
10461 // since they usually mess up the template instead of fixing the problem.
10462 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010463 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10464 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010465 return true;
10466 }
10467
10468 if (isDefinition) {
10469 // On definitions, check previous tags and issue a fix-it for each
10470 // one that doesn't match the current tag.
10471 if (Previous->getDefinition()) {
10472 // Don't suggest fix-its for redefinitions.
10473 return true;
10474 }
10475
10476 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010477 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010478 if (I->getTagKind() != NewTag) {
10479 if (!previousMismatch) {
10480 previousMismatch = true;
10481 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010482 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10483 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010484 }
10485 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010486 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010487 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010488 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010489 }
10490 }
10491 return true;
10492 }
10493
10494 // Check for a previous definition. If current tag and definition
10495 // are same type, do nothing. If no definition, but disagree with
10496 // with previous tag type, give a warning, but no fix-it.
10497 const TagDecl *Redecl = Previous->getDefinition() ?
10498 Previous->getDefinition() : Previous;
10499 if (Redecl->getTagKind() == NewTag) {
10500 return true;
10501 }
10502
Douglas Gregord9034f02009-05-14 16:41:31 +000010503 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010504 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10505 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010506 Diag(Redecl->getLocation(), diag::note_previous_use);
10507
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010508 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010509 if (Previous->getDefinition()) {
10510 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010511 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010512 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010513 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010514 }
10515
Douglas Gregord9034f02009-05-14 16:41:31 +000010516 return true;
10517 }
10518 return false;
10519}
10520
Steve Naroff30d242c2007-09-15 18:49:24 +000010521/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010522/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010523/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010524/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010525///
10526/// IsTypeSpecifier is true if this is a type-specifier (or
10527/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010528Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010529 SourceLocation KWLoc, CXXScopeSpec &SS,
10530 IdentifierInfo *Name, SourceLocation NameLoc,
10531 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010532 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010533 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010534 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010535 SourceLocation ScopedEnumKWLoc,
10536 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010537 TypeResult UnderlyingType,
10538 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010539 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010540 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010541 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010542 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010543 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010544
Douglas Gregord6ab8742009-05-28 23:31:59 +000010545 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010546 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010547 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010548
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010549 // FIXME: Check explicit specializations more carefully.
10550 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010551 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010552
10553 // We only need to do this matching if we have template parameters
10554 // or a scope specifier, which also conveniently avoids this work
10555 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010556 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010557 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010558 if (TemplateParameterList *TemplateParams =
10559 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +000010560 KWLoc, NameLoc, SS, 0, TemplateParameterLists,
10561 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010562 if (Kind == TTK_Enum) {
10563 Diag(KWLoc, diag::err_enum_template);
10564 return 0;
10565 }
10566
Douglas Gregor3dad8422009-09-26 06:47:28 +000010567 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010568 // This is a declaration or definition of a class template (which may
10569 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010570
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010571 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010572 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010573
Douglas Gregore93e46c2009-07-22 23:48:44 +000010574 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010575 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010576 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010577 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010578 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010579 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010580 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010581 return Result.get();
10582 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010583 // The "template<>" header is extraneous.
10584 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010585 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010586 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010587 }
Mike Stump11289f42009-09-09 15:08:12 +000010588 }
10589 }
10590
Douglas Gregor0bf31402010-10-08 23:50:27 +000010591 // Figure out the underlying type if this a enum declaration. We need to do
10592 // this early, because it's needed to detect if this is an incompatible
10593 // redeclaration.
10594 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10595
10596 if (Kind == TTK_Enum) {
10597 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10598 // No underlying type explicitly specified, or we failed to parse the
10599 // type, default to int.
10600 EnumUnderlying = Context.IntTy.getTypePtr();
10601 else if (UnderlyingType.get()) {
10602 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10603 // integral type; any cv-qualification is ignored.
10604 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010605 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010606 EnumUnderlying = TI;
10607
Richard Smith4b38ded2012-03-14 23:13:10 +000010608 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010609 // Recover by falling back to int.
10610 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010611
Richard Smith4b38ded2012-03-14 23:13:10 +000010612 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010613 UPPC_FixedUnderlyingType))
10614 EnumUnderlying = Context.IntTy.getTypePtr();
10615
Alp Tokerbfa39342014-01-14 12:51:41 +000010616 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010617 // Microsoft enums are always of int type.
10618 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010619 }
10620
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010621 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010622 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010623 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010624
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010625 RedeclarationKind Redecl = ForRedeclaration;
10626 if (TUK == TUK_Friend || TUK == TUK_Reference)
10627 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010628
10629 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010630 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010631 if (Name && SS.isNotEmpty()) {
10632 // We have a nested-name tag ('struct foo::bar').
10633
10634 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010635 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010636 Name = 0;
10637 goto CreateNewDecl;
10638 }
10639
John McCall7f41d982009-09-11 04:59:25 +000010640 // If this is a friend or a reference to a class in a dependent
10641 // context, don't try to make a decl for it.
10642 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10643 DC = computeDeclContext(SS, false);
10644 if (!DC) {
10645 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010646 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010647 }
John McCall0b66eb32010-05-01 00:40:08 +000010648 } else {
10649 DC = computeDeclContext(SS, true);
10650 if (!DC) {
10651 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10652 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010653 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010654 }
John McCall7f41d982009-09-11 04:59:25 +000010655 }
10656
John McCall0b66eb32010-05-01 00:40:08 +000010657 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010658 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010659
Douglas Gregor8761da52009-02-03 00:34:39 +000010660 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010661 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010662 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010663
John McCall1f82f242009-11-18 22:49:29 +000010664 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010665 return 0;
John McCall6538c932009-10-10 05:48:19 +000010666
John McCall1f82f242009-11-18 22:49:29 +000010667 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010668 // Name lookup did not find anything. However, if the
10669 // nested-name-specifier refers to the current instantiation,
10670 // and that current instantiation has any dependent base
10671 // classes, we might find something at instantiation time: treat
10672 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010673 // But this only makes any sense for reference-like lookups.
10674 if (Previous.wasNotFoundInCurrentInstantiation() &&
10675 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010676 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010677 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010678 }
10679
10680 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010681 Diag(NameLoc, diag::err_not_tag_in_scope)
10682 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010683 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010684 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010685 goto CreateNewDecl;
10686 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010687 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010688 // If this is a named struct, check to see if there was a previous forward
10689 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010690 // FIXME: We're looking into outer scopes here, even when we
10691 // shouldn't be. Doing so can result in ambiguities that we
10692 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010693 LookupName(Previous, S);
10694
John McCall3c581bf2013-03-20 01:53:00 +000010695 // When declaring or defining a tag, ignore ambiguities introduced
10696 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010697 if (Previous.isAmbiguous() &&
10698 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010699 LookupResult::Filter F = Previous.makeFilter();
10700 while (F.hasNext()) {
10701 NamedDecl *ND = F.next();
10702 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10703 F.erase();
10704 }
10705 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010706 }
John McCall3c581bf2013-03-20 01:53:00 +000010707
10708 // C++11 [namespace.memdef]p3:
10709 // If the name in a friend declaration is neither qualified nor
10710 // a template-id and the declaration is a function or an
10711 // elaborated-type-specifier, the lookup to determine whether
10712 // the entity has been previously declared shall not consider
10713 // any scopes outside the innermost enclosing namespace.
10714 //
10715 // Does it matter that this should be by scope instead of by
10716 // semantic context?
10717 if (!Previous.empty() && TUK == TUK_Friend) {
10718 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10719 LookupResult::Filter F = Previous.makeFilter();
10720 while (F.hasNext()) {
10721 NamedDecl *ND = F.next();
10722 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010723 if (DC->isFileContext() &&
10724 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010725 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010726 FriendSawTagOutsideEnclosingNamespace = true;
10727 }
John McCall3c581bf2013-03-20 01:53:00 +000010728 }
10729 F.done();
10730 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010731
John McCall1f82f242009-11-18 22:49:29 +000010732 // Note: there used to be some attempt at recovery here.
10733 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010734 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010735
David Blaikiebbafb8a2012-03-11 07:00:24 +000010736 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010737 // FIXME: This makes sure that we ignore the contexts associated
10738 // with C structs, unions, and enums when looking for a matching
10739 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010740 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010741 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10742 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010743 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010744 } else if (S->isFunctionPrototypeScope()) {
10745 // If this is an enum declaration in function prototype scope, set its
10746 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010747 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010748 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010749 }
10750
John McCall1f82f242009-11-18 22:49:29 +000010751 if (Previous.isSingleResult() &&
10752 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010753 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010754 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010755 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010756 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010757 }
10758
David Blaikiebbafb8a2012-03-11 07:00:24 +000010759 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010760 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010761 // This is a declaration of or a reference to "std::bad_alloc".
10762 isStdBadAlloc = true;
10763
John McCall1f82f242009-11-18 22:49:29 +000010764 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010765 // std::bad_alloc has been implicitly declared (but made invisible to
10766 // name lookup). Fill in this implicit declaration as the previous
10767 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010768 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010769 }
10770 }
John McCall1f82f242009-11-18 22:49:29 +000010771
John McCalle9eaf8e2010-03-25 21:28:06 +000010772 // If we didn't find a previous declaration, and this is a reference
10773 // (or friend reference), move to the correct scope. In C++, we
10774 // also need to do a redeclaration lookup there, just in case
10775 // there's a shadow friend decl.
10776 if (Name && Previous.empty() &&
10777 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10778 if (Invalid) goto CreateNewDecl;
10779 assert(SS.isEmpty());
10780
10781 if (TUK == TUK_Reference) {
10782 // C++ [basic.scope.pdecl]p5:
10783 // -- for an elaborated-type-specifier of the form
10784 //
10785 // class-key identifier
10786 //
10787 // if the elaborated-type-specifier is used in the
10788 // decl-specifier-seq or parameter-declaration-clause of a
10789 // function defined in namespace scope, the identifier is
10790 // declared as a class-name in the namespace that contains
10791 // the declaration; otherwise, except as a friend
10792 // declaration, the identifier is declared in the smallest
10793 // non-class, non-function-prototype scope that contains the
10794 // declaration.
10795 //
10796 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10797 // C structs and unions.
10798 //
10799 // It is an error in C++ to declare (rather than define) an enum
10800 // type, including via an elaborated type specifier. We'll
10801 // diagnose that later; for now, declare the enum in the same
10802 // scope as we would have picked for any other tag type.
10803 //
10804 // GNU C also supports this behavior as part of its incomplete
10805 // enum types extension, while GNU C++ does not.
10806 //
10807 // Find the context where we'll be declaring the tag.
10808 // FIXME: We would like to maintain the current DeclContext as the
10809 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010810 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010811 SearchDC = SearchDC->getParent();
10812
10813 // Find the scope where we'll be declaring the tag.
10814 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010815 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010816 S->isFunctionPrototypeScope()) ||
10817 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010818 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010819 S = S->getParent();
10820 } else {
10821 assert(TUK == TUK_Friend);
10822 // C++ [namespace.memdef]p3:
10823 // If a friend declaration in a non-local class first declares a
10824 // class or function, the friend class or function is a member of
10825 // the innermost enclosing namespace.
10826 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010827 }
10828
John McCalle87beb22010-04-23 18:46:30 +000010829 // In C++, we need to do a redeclaration lookup to properly
10830 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010831 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010832 Previous.setRedeclarationKind(ForRedeclaration);
10833 LookupQualifiedName(Previous, SearchDC);
10834 }
10835 }
10836
John McCall1f82f242009-11-18 22:49:29 +000010837 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010838 NamedDecl *PrevDecl = Previous.getFoundDecl();
10839 NamedDecl *DirectPrevDecl =
10840 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010841
10842 // It's okay to have a tag decl in the same scope as a typedef
10843 // which hides a tag decl in the same scope. Finding this
10844 // insanity with a redeclaration lookup can only actually happen
10845 // in C++.
10846 //
10847 // This is also okay for elaborated-type-specifiers, which is
10848 // technically forbidden by the current standard but which is
10849 // okay according to the likely resolution of an open issue;
10850 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010851 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010852 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010853 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10854 TagDecl *Tag = TT->getDecl();
10855 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010856 Tag->getDeclContext()->getRedeclContext()
10857 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010858 PrevDecl = Tag;
10859 Previous.clear();
10860 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010861 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010862 }
10863 }
10864 }
10865 }
10866
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010867 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010868 // If this is a use of a previous tag, or if the tag is already declared
10869 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010870 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010871 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010872 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010873 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010874 // Make sure that this wasn't declared as an enum and now used as a
10875 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010876 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10877 TUK == TUK_Definition, KWLoc,
10878 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010879 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010880 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10881 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010882 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010883 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010884 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010885 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10886 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010887 else
10888 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010889 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010890
Mike Stump11289f42009-09-09 15:08:12 +000010891 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010892 Kind = PrevTagDecl->getTagKind();
10893 else {
10894 // Recover by making this an anonymous redefinition.
10895 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010896 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010897 Invalid = true;
10898 }
10899 }
10900
Douglas Gregor0bf31402010-10-08 23:50:27 +000010901 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10902 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10903
Richard Smith0f8ee222012-01-10 01:33:14 +000010904 // If this is an elaborated-type-specifier for a scoped enumeration,
10905 // the 'class' keyword is not necessary and not permitted.
10906 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10907 if (ScopedEnum)
10908 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10909 << PrevEnum->isScoped()
10910 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10911 return PrevTagDecl;
10912 }
10913
Richard Smith4b38ded2012-03-14 23:13:10 +000010914 QualType EnumUnderlyingTy;
10915 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010916 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010917 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10918 EnumUnderlyingTy = QualType(T, 0);
10919
Douglas Gregor0bf31402010-10-08 23:50:27 +000010920 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010921 // returning the previous declaration, unless this is a definition,
10922 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010923 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10924 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010925 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010926 }
10927
David Majnemer55890bf2013-06-11 03:51:23 +000010928 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010929 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010930 // except that a nested class or member class template can be declared
10931 // and then later defined.
10932 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10933 S->isDeclScope(PrevDecl)) {
10934 Diag(NameLoc, diag::ext_member_redeclared);
10935 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10936 }
10937
Douglas Gregor170512f2009-04-01 23:51:29 +000010938 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010939 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010940
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010941 // FIXME: In the future, return a variant or some other clue
10942 // for the consumer of this Decl to know it doesn't own it.
10943 // For our current ASTs this shouldn't be a problem, but will
10944 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010945 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010946 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010947 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010948
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010949 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010950 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010951 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010952 // If we're defining a specialization and the previous definition
10953 // is from an implicit instantiation, don't emit an error
10954 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010955 bool IsExplicitSpecializationAfterInstantiation = false;
10956 if (isExplicitSpecialization) {
10957 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10958 IsExplicitSpecializationAfterInstantiation =
10959 RD->getTemplateSpecializationKind() !=
10960 TSK_ExplicitSpecialization;
10961 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10962 IsExplicitSpecializationAfterInstantiation =
10963 ED->getTemplateSpecializationKind() !=
10964 TSK_ExplicitSpecialization;
10965 }
10966
10967 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010968 // A redeclaration in function prototype scope in C isn't
10969 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010970 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010971 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10972 else
10973 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010974 Diag(Def->getLocation(), diag::note_previous_definition);
10975 // If this is a redefinition, recover by making this
10976 // struct be anonymous, which will make any later
10977 // references get the previous definition.
10978 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010979 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010980 Invalid = true;
10981 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010982 } else {
10983 // If the type is currently being defined, complain
10984 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010985 const TagType *Tag
10986 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010987 if (Tag->isBeingDefined()) {
10988 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010989 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010990 diag::note_previous_definition);
10991 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010992 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010993 Invalid = true;
10994 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010995 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010996
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010997 // Okay, this is definition of a previously declared or referenced
10998 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010999 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011000 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011001 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000011002 // have a definition. Just create a new decl.
11003
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011004 } else {
11005 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000011006 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011007 // new decl/type. We set PrevDecl to NULL so that the entities
11008 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000011009 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000011010 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011011 // If we get here, we're going to create a new Decl. If PrevDecl
11012 // is non-NULL, it's a definition of the tag declared by
11013 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000011014
11015
11016 // Otherwise, PrevDecl is not a tag, but was found with tag
11017 // lookup. This is only actually possible in C++, where a few
11018 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011019 } else {
John McCalle87beb22010-04-23 18:46:30 +000011020 // Use a better diagnostic if an elaborated-type-specifier
11021 // found the wrong kind of type on the first
11022 // (non-redeclaration) lookup.
11023 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11024 !Previous.isForRedeclaration()) {
11025 unsigned Kind = 0;
11026 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011027 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11028 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011029 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11030 Diag(PrevDecl->getLocation(), diag::note_declared_at);
11031 Invalid = true;
11032
11033 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000011034 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11035 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000011036 // do nothing
11037
11038 // Diagnose implicit declarations introduced by elaborated types.
11039 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11040 unsigned Kind = 0;
11041 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011042 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11043 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011044 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11045 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11046 Invalid = true;
11047
11048 // Otherwise it's a declaration. Call out a particularly common
11049 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000011050 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11051 unsigned Kind = 0;
11052 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000011053 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000011054 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000011055 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11056 Invalid = true;
11057
11058 // Otherwise, diagnose.
11059 } else {
11060 // The tag name clashes with something else in the target scope,
11061 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000011062 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000011063 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011064 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000011065 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011066 }
John McCalle87beb22010-04-23 18:46:30 +000011067
11068 // The existing declaration isn't relevant to us; we're in a
11069 // new scope, so clear out the previous declaration.
11070 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000011071 }
Chris Lattner18b19622007-01-22 07:39:13 +000011072 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000011073
Chris Lattner438e5012008-12-17 07:13:27 +000011074CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000011075
John McCall1f82f242009-11-18 22:49:29 +000011076 TagDecl *PrevDecl = 0;
11077 if (Previous.isSingleResult())
11078 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11079
Chris Lattnerbf0b7982007-01-23 04:27:41 +000011080 // If there is an identifier, use the location of the identifier as the
11081 // location of the decl, otherwise use the location of the struct/union
11082 // keyword.
11083 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000011084
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011085 // Otherwise, create a new declaration. If there is a previous
11086 // declaration of the same entity, the two will be linked via
11087 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000011088 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000011089
Douglas Gregor0bf31402010-10-08 23:50:27 +000011090 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000011091 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000011092 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11093 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011094 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000011095 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000011096 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000011097 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011098 if (TUK != TUK_Definition && !Invalid) {
11099 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000011100 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11101 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000011102 // C++0x: 7.2p2: opaque-enum-declaration.
11103 // Conflicts are diagnosed above. Do nothing.
11104 }
11105 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011106 Diag(Loc, diag::ext_forward_ref_enum_def)
11107 << New;
11108 Diag(Def->getLocation(), diag::note_previous_definition);
11109 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000011110 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000011111 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000011112 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011113 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000011114 DiagID = diag::err_forward_ref_enum;
11115 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011116
11117 // If this is a forward-declared reference to an enumeration, make a
11118 // note of it; we won't actually be introducing the declaration into
11119 // the declaration context.
11120 if (TUK == TUK_Reference)
11121 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011122 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000011123 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000011124
11125 if (EnumUnderlying) {
11126 EnumDecl *ED = cast<EnumDecl>(New);
11127 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11128 ED->setIntegerTypeSourceInfo(TI);
11129 else
11130 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11131 ED->setPromotionType(ED->getIntegerType());
11132 }
11133
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011134 } else {
11135 // struct/union/class
11136
Chris Lattner776fac82007-06-09 00:53:06 +000011137 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11138 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011139 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000011140 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011141 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011142 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011143
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011144 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000011145 StdBadAlloc = cast<CXXRecordDecl>(New);
11146 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011147 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011148 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011149 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011150
Richard Smith649c7b062014-01-08 00:56:48 +000011151 // C++11 [dcl.type]p3:
11152 // A type-specifier-seq shall not define a class or enumeration [...].
11153 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11154 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11155 << Context.getTagDeclType(New);
11156 Invalid = true;
11157 }
11158
John McCall3e11ebe2010-03-15 10:12:16 +000011159 // Maybe add qualifier info.
11160 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011161 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011162 // If this is either a declaration or a definition, check the
11163 // nested-name-specifier against the current context. We don't do this
11164 // for explicit specializations, because they have similar checking
11165 // (with more specific diagnostics) in the call to
11166 // CheckMemberSpecialization, below.
11167 if (!isExplicitSpecialization &&
11168 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11169 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11170 Invalid = true;
11171
Douglas Gregor14454802011-02-25 02:25:35 +000011172 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011173 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011174 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011175 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011176 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011177 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011178 }
11179 else
11180 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011181 }
11182
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011183 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11184 // Add alignment attributes if necessary; these attributes are checked when
11185 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011186 //
11187 // It is important for implementing the correct semantics that this
11188 // happen here (in act on tag decl). The #pragma pack stack is
11189 // maintained as a result of parser callbacks which can occur at
11190 // many points during the parsing of a struct declaration (because
11191 // the #pragma tokens are effectively skipped over during the
11192 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011193 if (TUK == TUK_Definition) {
11194 AddAlignmentAttributesForRecord(RD);
11195 AddMsStructLayoutForRecord(RD);
11196 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011197 }
11198
Douglas Gregor21823bf2011-12-20 18:11:52 +000011199 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011200 if (isExplicitSpecialization)
11201 Diag(New->getLocation(), diag::err_module_private_specialization)
11202 << 2
11203 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011204 // __module_private__ does not apply to local classes. However, we only
11205 // diagnose this as an error when the declaration specifiers are
11206 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011207 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011208 New->setModulePrivate();
11209 }
11210
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011211 // If this is a specialization of a member class (of a class template),
11212 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011213 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011214 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011215
Douglas Gregordee1be82009-01-17 00:42:38 +000011216 if (Invalid)
11217 New->setInvalidDecl();
11218
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011219 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011220 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011221
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011222 // If we're declaring or defining a tag in function prototype scope in C,
11223 // note that this type can only be used within the function and add it to
11224 // the list of decls to inject into the function definition scope.
11225 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11226 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
Douglas Gregor658b9552009-01-09 22:42:13 +000011227 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011228 DeclsInPrototypeScope.push_back(New);
11229 }
Douglas Gregor658b9552009-01-09 22:42:13 +000011230
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011231 // Set the lexical context. If the tag has a C++ scope specifier, the
11232 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011233 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011234
John McCallaa74a0c2009-08-28 07:59:38 +000011235 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011236 // In Microsoft mode, a friend declaration also acts as a forward
11237 // declaration so we always pass true to setObjectOfFriendDecl to make
11238 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011239 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011240 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11241 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011242
Anders Carlsson5558ca12009-03-26 01:19:02 +000011243 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011244 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011245 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011246
John McCall9bb74a52009-07-31 02:45:11 +000011247 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011248 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011249
Chris Lattner18b19622007-01-22 07:39:13 +000011250 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011251 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011252 // We might be replacing an existing declaration in the lookup tables;
11253 // if so, borrow its access specifier.
11254 if (PrevDecl)
11255 New->setAccess(PrevDecl->getAccess());
11256
Sebastian Redl50c68252010-08-31 00:36:30 +000011257 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011258 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011259 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011260 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11261 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011262 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011263 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011264 PushOnScopeChains(New, S, !IsForwardReference);
11265 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011266 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011267
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011268 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011269 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011270 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011271
Douglas Gregor27821ce2009-07-07 16:35:42 +000011272 // If this is the C FILE type, notify the AST context.
11273 if (IdentifierInfo *II = New->getIdentifier())
11274 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011275 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011276 II->isStr("FILE"))
11277 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011278
Rafael Espindolac67f2232012-05-10 02:50:16 +000011279 if (PrevDecl)
11280 mergeDeclAttributes(New, PrevDecl);
11281
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011282 // If there's a #pragma GCC visibility in scope, set the visibility of this
11283 // record.
11284 AddPushedVisibilityAttribute(New);
11285
Douglas Gregord6ab8742009-05-28 23:31:59 +000011286 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011287 // In C++, don't return an invalid declaration. We can't recover well from
11288 // the cases where we make the type anonymous.
11289 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011290}
Chris Lattner1300fb92007-01-23 23:42:53 +000011291
John McCall48871652010-08-21 09:40:31 +000011292void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011293 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011294 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011295
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011296 // Enter the tag context.
11297 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011298
11299 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011300
11301 // If there's a #pragma GCC visibility in scope, set the visibility of this
11302 // record.
11303 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011304}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011305
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011306Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011307 assert(isa<ObjCContainerDecl>(IDecl) &&
11308 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11309 DeclContext *OCD = cast<DeclContext>(IDecl);
11310 assert(getContainingDC(OCD) == CurContext &&
11311 "The next DeclContext should be lexically contained in the current one.");
11312 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011313 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011314}
11315
John McCall48871652010-08-21 09:40:31 +000011316void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011317 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011318 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011319 SourceLocation LBraceLoc) {
11320 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011321 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011322
John McCall1c7e6ec2009-12-20 07:58:13 +000011323 FieldCollector->StartClass();
11324
11325 if (!Record->getIdentifier())
11326 return;
11327
Anders Carlsson30f29442011-03-25 14:31:08 +000011328 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011329 Record->addAttr(new (Context)
11330 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11331
John McCall1c7e6ec2009-12-20 07:58:13 +000011332 // C++ [class]p2:
11333 // [...] The class-name is also inserted into the scope of the
11334 // class itself; this is known as the injected-class-name. For
11335 // purposes of access checking, the injected-class-name is treated
11336 // as if it were a public member name.
11337 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011338 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11339 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011340 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011341 /*PrevDecl=*/0,
11342 /*DelayTypeCreation=*/true);
11343 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011344 InjectedClassName->setImplicit();
11345 InjectedClassName->setAccess(AS_public);
11346 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11347 InjectedClassName->setDescribedClassTemplate(Template);
11348 PushOnScopeChains(InjectedClassName, S);
11349 assert(InjectedClassName->isInjectedClassName() &&
11350 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011351}
11352
John McCall48871652010-08-21 09:40:31 +000011353void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011354 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011355 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011356 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011357 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011358
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011359 // Make sure we "complete" the definition even it is invalid.
11360 if (Tag->isBeingDefined()) {
11361 assert(Tag->isInvalidDecl() && "We should already have completed it");
11362 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11363 RD->completeDefinition();
11364 }
11365
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011366 if (isa<CXXRecordDecl>(Tag))
11367 FieldCollector->FinishClass();
11368
11369 // Exit this scope of this tag's definition.
11370 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011371
11372 if (getCurLexicalContext()->isObjCContainer() &&
11373 Tag->getDeclContext()->isFileContext())
11374 Tag->setTopLevelDeclInObjCContainer();
11375
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011376 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011377 if (!Tag->isInvalidDecl())
11378 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011379}
Chris Lattner535b8302008-06-21 19:39:06 +000011380
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011381void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011382 // Exit this scope of this interface definition.
11383 PopDeclContext();
11384}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011385
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011386void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011387 assert(DC == CurContext && "Mismatch of container contexts");
11388 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011389 ActOnObjCContainerFinishDefinition();
11390}
11391
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011392void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11393 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011394 OriginalLexicalContext = 0;
11395}
11396
John McCall48871652010-08-21 09:40:31 +000011397void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011398 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011399 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011400 Tag->setInvalidDecl();
11401
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011402 // Make sure we "complete" the definition even it is invalid.
11403 if (Tag->isBeingDefined()) {
11404 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11405 RD->completeDefinition();
11406 }
11407
John McCall71ba5f22010-03-17 19:25:57 +000011408 // We're undoing ActOnTagStartDefinition here, not
11409 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11410 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011411
11412 PopDeclContext();
11413}
11414
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011415// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011416ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11417 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011418 QualType FieldTy, bool IsMsStruct,
11419 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011420 // Default to true; that shouldn't confuse checks for emptiness
11421 if (ZeroWidth)
11422 *ZeroWidth = true;
11423
Chris Lattner73bf7b42009-03-05 22:45:59 +000011424 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011425 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011426 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011427 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011428 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011429 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011430 if (FieldName)
11431 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11432 << FieldName << FieldTy << BitWidth->getSourceRange();
11433 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11434 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011435 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11436 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011437 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011438
11439 // If the bit-width is type- or value-dependent, don't try to check
11440 // it now.
11441 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011442 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011443
Anders Carlsson5df391e2008-12-06 20:33:04 +000011444 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011445 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11446 if (ICE.isInvalid())
11447 return ICE;
11448 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011449
Eli Friedmanc96d4962009-08-15 21:55:26 +000011450 if (Value != 0 && ZeroWidth)
11451 *ZeroWidth = false;
11452
Chris Lattner81ed6802008-12-12 04:56:04 +000011453 // Zero-width bitfield is ok for anonymous field.
11454 if (Value == 0 && FieldName)
11455 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011456
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011457 if (Value.isSigned() && Value.isNegative()) {
11458 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011459 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011460 << FieldName << Value.toString(10);
11461 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11462 << Value.toString(10);
11463 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011464
Douglas Gregor1efa4372009-03-11 18:59:21 +000011465 if (!FieldTy->isDependentType()) {
11466 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011467 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011468 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11469 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011470 if (FieldName)
11471 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11472 << FieldName << (unsigned)Value.getZExtValue()
11473 << (unsigned)TypeSize;
11474
11475 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11476 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11477 }
11478
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011479 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011480 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11481 << FieldName << (unsigned)Value.getZExtValue()
11482 << (unsigned)TypeSize;
11483 else
11484 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11485 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011486 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011487 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011488
Richard Smithf4c51d92012-02-04 09:53:13 +000011489 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011490}
11491
Richard Smith938f40b2011-06-11 17:19:42 +000011492/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011493/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011494Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011495 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011496 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011497 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011498 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011499 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011500}
11501
11502/// HandleField - Analyze a field of a C struct or a C++ data member.
11503///
11504FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11505 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011506 Declarator &D, Expr *BitWidth,
11507 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011508 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011509 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011510 SourceLocation Loc = DeclStart;
11511 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011512
John McCall8cb7bdf2010-06-04 23:28:52 +000011513 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11514 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011515 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011516 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011517
Douglas Gregora02a72a2010-12-15 23:18:36 +000011518 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11519 UPPC_DataMemberType)) {
11520 D.setInvalidType();
11521 T = Context.IntTy;
11522 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11523 }
11524 }
11525
Matt Arsenault376f7202013-02-26 21:16:00 +000011526 // TR 18037 does not allow fields to be declared with address spaces.
11527 if (T.getQualifiers().hasAddressSpace()) {
11528 Diag(Loc, diag::err_field_with_address_space);
11529 D.setInvalidType();
11530 }
11531
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011532 // OpenCL 1.2 spec, s6.9 r:
11533 // The event type cannot be used to declare a structure or union field.
11534 if (LangOpts.OpenCL && T->isEventT()) {
11535 Diag(Loc, diag::err_event_t_struct_field);
11536 D.setInvalidType();
11537 }
11538
Richard Smithb1402ae2013-03-18 22:52:47 +000011539 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011540
Richard Smithb4a9e862013-04-12 22:46:28 +000011541 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11542 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11543 diag::err_invalid_thread)
11544 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011545
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011546 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011547 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011548 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11549 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011550 switch (Previous.getResultKind()) {
11551 case LookupResult::Found:
11552 case LookupResult::FoundUnresolvedValue:
11553 PrevDecl = Previous.getAsSingle<NamedDecl>();
11554 break;
11555
11556 case LookupResult::FoundOverloaded:
11557 PrevDecl = Previous.getRepresentativeDecl();
11558 break;
11559
11560 case LookupResult::NotFound:
11561 case LookupResult::NotFoundInCurrentInstantiation:
11562 case LookupResult::Ambiguous:
11563 break;
11564 }
11565 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011566
11567 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11568 // Maybe we will complain about the shadowed template parameter.
11569 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11570 // Just pretend that we didn't see the previous declaration.
11571 PrevDecl = 0;
11572 }
11573
Douglas Gregor1efa4372009-03-11 18:59:21 +000011574 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11575 PrevDecl = 0;
11576
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011577 bool Mutable
11578 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011579 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011580 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011581 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011582 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011583
11584 if (NewFD->isInvalidDecl())
11585 Record->setInvalidDecl();
11586
Douglas Gregor3baa6702011-09-12 16:11:24 +000011587 if (D.getDeclSpec().isModulePrivateSpecified())
11588 NewFD->setModulePrivate();
11589
Douglas Gregor1efa4372009-03-11 18:59:21 +000011590 if (NewFD->isInvalidDecl() && PrevDecl) {
11591 // Don't introduce NewFD into scope; there's already something
11592 // with the same name in the same scope.
11593 } else if (II) {
11594 PushOnScopeChains(NewFD, S);
11595 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011596 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011597
11598 return NewFD;
11599}
11600
11601/// \brief Build a new FieldDecl and check its well-formedness.
11602///
11603/// This routine builds a new FieldDecl given the fields name, type,
11604/// record, etc. \p PrevDecl should refer to any previous declaration
11605/// with the same name and in the same scope as the field to be
11606/// created.
11607///
11608/// \returns a new FieldDecl.
11609///
Mike Stump11289f42009-09-09 15:08:12 +000011610/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011611FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011612 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011613 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011614 bool Mutable, Expr *BitWidth,
11615 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011616 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011617 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011618 Declarator *D) {
11619 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011620 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011621 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011622
Douglas Gregor1efa4372009-03-11 18:59:21 +000011623 // If we receive a broken type, recover by assuming 'int' and
11624 // marking this declaration as invalid.
11625 if (T.isNull()) {
11626 InvalidDecl = true;
11627 T = Context.IntTy;
11628 }
11629
Eli Friedmand0e8de22009-12-07 00:22:08 +000011630 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011631 if (!EltTy->isDependentType()) {
11632 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11633 // Fields of incomplete type force their record to be invalid.
11634 Record->setInvalidDecl();
11635 InvalidDecl = true;
11636 } else {
11637 NamedDecl *Def;
11638 EltTy->isIncompleteType(&Def);
11639 if (Def && Def->isInvalidDecl()) {
11640 Record->setInvalidDecl();
11641 InvalidDecl = true;
11642 }
11643 }
John McCall2677e102010-08-16 23:42:35 +000011644 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011645
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011646 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11647 if (BitWidth && getLangOpts().OpenCL) {
11648 Diag(Loc, diag::err_opencl_bitfields);
11649 InvalidDecl = true;
11650 }
11651
Steve Naroff8eeeb132007-05-08 21:09:37 +000011652 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11653 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011654 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011655 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011656 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011657
11658 TypeSourceInfo *FixedTInfo =
11659 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11660 SizeIsNegative,
11661 Oversized);
11662 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011663 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011664 TInfo = FixedTInfo;
11665 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011666 } else {
11667 if (SizeIsNegative)
11668 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011669 else if (Oversized.getBoolValue())
11670 Diag(Loc, diag::err_array_too_large)
11671 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011672 else
11673 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011674 InvalidDecl = true;
11675 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011676 }
Mike Stump11289f42009-09-09 15:08:12 +000011677
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011678 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011679 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11680 diag::err_abstract_type_in_decl,
11681 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011682 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011683
Eli Friedmanc96d4962009-08-15 21:55:26 +000011684 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011685 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011686 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011687 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11688 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011689 if (!BitWidth) {
11690 InvalidDecl = true;
11691 BitWidth = 0;
11692 ZeroWidth = false;
11693 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011694 }
Mike Stump11289f42009-09-09 15:08:12 +000011695
John McCallb1cd7da2010-06-04 08:34:12 +000011696 // Check that 'mutable' is consistent with the type of the declaration.
11697 if (!InvalidDecl && Mutable) {
11698 unsigned DiagID = 0;
11699 if (T->isReferenceType())
11700 DiagID = diag::err_mutable_reference;
11701 else if (T.isConstQualified())
11702 DiagID = diag::err_mutable_const;
11703
11704 if (DiagID) {
11705 SourceLocation ErrLoc = Loc;
11706 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11707 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11708 Diag(ErrLoc, DiagID);
11709 Mutable = false;
11710 InvalidDecl = true;
11711 }
11712 }
11713
Richard Smithab44d5b2013-12-10 08:25:00 +000011714 // C++11 [class.union]p8 (DR1460):
11715 // At most one variant member of a union may have a
11716 // brace-or-equal-initializer.
11717 if (InitStyle != ICIS_NoInit)
11718 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11719
Abramo Bagnaradff19302011-03-08 08:55:46 +000011720 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011721 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011722 if (InvalidDecl)
11723 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011724
Douglas Gregor1efa4372009-03-11 18:59:21 +000011725 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11726 Diag(Loc, diag::err_duplicate_member) << II;
11727 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11728 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011729 }
11730
David Blaikiebbafb8a2012-03-11 07:00:24 +000011731 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011732 if (Record->isUnion()) {
11733 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11734 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11735 if (RDecl->getDefinition()) {
11736 // C++ [class.union]p1: An object of a class with a non-trivial
11737 // constructor, a non-trivial copy constructor, a non-trivial
11738 // destructor, or a non-trivial copy assignment operator
11739 // cannot be a member of a union, nor can an array of such
11740 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011741 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011742 NewFD->setInvalidDecl();
11743 }
11744 }
11745
11746 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011747 // the program is ill-formed, except when compiling with MSVC extensions
11748 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011749 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011750 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11751 diag::ext_union_member_of_reference_type :
11752 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011753 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011754 if (!getLangOpts().MicrosoftExt)
11755 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011756 }
11757 }
11758 }
11759
Douglas Gregor1efa4372009-03-11 18:59:21 +000011760 // FIXME: We need to pass in the attributes given an AST
11761 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011762 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011763 // FIXME: The current scope is almost... but not entirely... correct here.
11764 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011765
Richard Smith848e1f12013-02-01 08:12:08 +000011766 if (NewFD->hasAttrs())
11767 CheckAlignasUnderalignment(NewFD);
11768 }
11769
John McCall31168b02011-06-15 23:02:42 +000011770 // In auto-retain/release, infer strong retension for fields of
11771 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011772 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011773 NewFD->setInvalidDecl();
11774
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011775 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011776 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011777
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011778 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011779 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011780}
11781
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011782bool Sema::CheckNontrivialField(FieldDecl *FD) {
11783 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011784 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011785
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011786 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11787 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011788
11789 QualType EltTy = Context.getBaseElementType(FD->getType());
11790 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011791 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011792 if (RDecl->getDefinition()) {
11793 // We check for copy constructors before constructors
11794 // because otherwise we'll never get complaints about
11795 // copy constructors.
11796
11797 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011798 // We're required to check for any non-trivial constructors. Since the
11799 // implicit default constructor is suppressed if there are any
11800 // user-declared constructors, we just need to check that there is a
11801 // trivial default constructor and a trivial copy constructor. (We don't
11802 // worry about move constructors here, since this is a C++98 check.)
11803 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011804 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011805 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011806 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011807 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011808 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011809 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011810 member = CXXDestructor;
11811
11812 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011813 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011814 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011815 // Objective-C++ ARC: it is an error to have a non-trivial field of
11816 // a union. However, system headers in Objective-C programs
11817 // occasionally have Objective-C lifetime objects within unions,
11818 // and rather than cause the program to fail, we make those
11819 // members unavailable.
11820 SourceLocation Loc = FD->getLocation();
11821 if (getSourceManager().isInSystemHeader(Loc)) {
11822 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011823 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11824 "this system field has retaining ownership",
11825 Loc));
John McCall31168b02011-06-15 23:02:42 +000011826 return false;
11827 }
11828 }
Richard Smithf720df02011-10-19 20:41:51 +000011829
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011830 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011831 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11832 diag::err_illegal_union_or_anon_struct_member)
11833 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011834 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011835 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011836 }
11837 }
11838 }
Richard Smith92f241f2012-12-08 02:53:02 +000011839
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011840 return false;
11841}
11842
Mike Stump11289f42009-09-09 15:08:12 +000011843/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011844/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011845static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011846TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011847 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011848 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011849 case tok::objc_private: return ObjCIvarDecl::Private;
11850 case tok::objc_public: return ObjCIvarDecl::Public;
11851 case tok::objc_protected: return ObjCIvarDecl::Protected;
11852 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011853 }
11854}
11855
Mike Stump11289f42009-09-09 15:08:12 +000011856/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011857/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011858Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011859 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011860 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011861 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011862
Fariborz Jahaniande615832008-04-10 23:32:45 +000011863 IdentifierInfo *II = D.getIdentifier();
11864 Expr *BitWidth = (Expr*)BitfieldWidth;
11865 SourceLocation Loc = DeclStart;
11866 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011867
Fariborz Jahaniande615832008-04-10 23:32:45 +000011868 // FIXME: Unnamed fields can be handled in various different ways, for
11869 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011870
John McCall8cb7bdf2010-06-04 23:28:52 +000011871 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11872 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011873
Fariborz Jahaniande615832008-04-10 23:32:45 +000011874 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011875 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011876 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011877 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011878 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011879 } else {
11880 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011881
Fariborz Jahaniande615832008-04-10 23:32:45 +000011882 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011883
Fariborz Jahaniande615832008-04-10 23:32:45 +000011884 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011885 if (T->isReferenceType()) {
11886 Diag(Loc, diag::err_ivar_reference_type);
11887 D.setInvalidType();
11888 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011889 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11890 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011891 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011892 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011893 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011894 }
Mike Stump11289f42009-09-09 15:08:12 +000011895
Ted Kremenek73295fa2008-07-23 18:04:17 +000011896 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011897 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011898 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11899 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011900 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011901 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011902 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11903 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011904 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011905 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011906 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011907 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011908 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011909 EnclosingContext = IMPDecl->getClassInterface();
11910 assert(EnclosingContext && "Implementation has no class interface!");
11911 }
11912 else
11913 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011914 } else {
11915 if (ObjCCategoryDecl *CDecl =
11916 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011917 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011918 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011919 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011920 }
11921 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011922 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011923 }
Mike Stump11289f42009-09-09 15:08:12 +000011924
Ted Kremenek73295fa2008-07-23 18:04:17 +000011925 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011926 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11927 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011928 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011929
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011930 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011931 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011932 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011933 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011934 && !isa<TagDecl>(PrevDecl)) {
11935 Diag(Loc, diag::err_duplicate_member) << II;
11936 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11937 NewID->setInvalidDecl();
11938 }
11939 }
11940
Ted Kremenek73295fa2008-07-23 18:04:17 +000011941 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011942 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011943
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011944 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011945 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011946
John McCall31168b02011-06-15 23:02:42 +000011947 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011948 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011949 NewID->setInvalidDecl();
11950
Douglas Gregor3baa6702011-09-12 16:11:24 +000011951 if (D.getDeclSpec().isModulePrivateSpecified())
11952 NewID->setModulePrivate();
11953
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011954 if (II) {
11955 // FIXME: When interfaces are DeclContexts, we'll need to add
11956 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011957 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011958 IdResolver.AddDecl(NewID);
11959 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011960
John McCall5fb5df92012-06-20 06:18:46 +000011961 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011962 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011963 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011964
John McCall48871652010-08-21 09:40:31 +000011965 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011966}
11967
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011968/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011969/// class and class extensions. For every class \@interface and class
11970/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011971/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011972void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011973 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011974 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011975 return;
11976
11977 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11978 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11979
Richard Smithcaf33902011-10-10 18:28:20 +000011980 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011981 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011982 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011983 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011984 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011985 if (!CD->IsClassExtension())
11986 return;
11987 }
11988 // No need to add this to end of @implementation.
11989 else
11990 return;
11991 }
11992 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011993 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11994 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011995
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011996 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011997 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011998 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011999 Context.getTrivialTypeSourceInfo(Context.CharTy,
12000 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012001 ObjCIvarDecl::Private, BW,
12002 true);
12003 AllIvarDecls.push_back(Ivar);
12004}
12005
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012006void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12007 ArrayRef<Decl *> Fields, SourceLocation LBrac,
12008 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000012009 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000012010
Eric Christopher7457aaf2012-07-19 22:22:51 +000012011 // If this is an Objective-C @implementation or category and we have
12012 // new fields here we should reset the layout of the interface since
12013 // it will now change.
12014 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12015 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12016 switch (DC->getKind()) {
12017 default: break;
12018 case Decl::ObjCCategory:
12019 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12020 break;
12021 case Decl::ObjCImplementation:
12022 Context.
12023 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12024 break;
12025 }
12026 }
12027
Eli Friedmana7679412012-02-07 05:00:47 +000012028 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12029
12030 // Start counting up the number of named members; make sure to include
12031 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000012032 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000012033 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000012034 for (const auto *I : Record->decls()) {
12035 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000012036 if (IFD->getDeclName())
12037 ++NumNamedMembers;
12038 }
12039 }
12040
12041 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012042 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000012043
John McCall31168b02011-06-15 23:02:42 +000012044 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012045 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000012046 i != end; ++i) {
12047 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000012048
Chris Lattner720a0542007-01-25 00:44:24 +000012049 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000012050 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000012051
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012052 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000012053 // Remember all fields written by the user.
12054 RecFields.push_back(FD);
12055 }
Mike Stump11289f42009-09-09 15:08:12 +000012056
Chris Lattner73bf7b42009-03-05 22:45:59 +000012057 // If the field is already invalid for some reason, don't emit more
12058 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000012059 if (FD->isInvalidDecl()) {
12060 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000012061 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000012062 }
Mike Stump11289f42009-09-09 15:08:12 +000012063
Douglas Gregorac1fb652009-03-24 19:52:54 +000012064 // C99 6.7.2.1p2:
12065 // A structure or union shall not contain a member with
12066 // incomplete or function type (hence, a structure shall not
12067 // contain an instance of itself, but may contain a pointer to
12068 // an instance of itself), except that the last member of a
12069 // structure with more than one named member may have incomplete
12070 // array type; such a structure (and any union containing,
12071 // possibly recursively, a member that is such a structure)
12072 // shall not be a member of a structure or an element of an
12073 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000012074 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012075 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000012076 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012077 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000012078 FD->setInvalidDecl();
12079 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012080 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000012081 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000012082 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000012083 ((getLangOpts().MicrosoftExt ||
12084 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000012085 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012086 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000012087 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000012088 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000012089 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000012090 unsigned DiagID = 0;
12091 if (Record->isUnion())
12092 DiagID = getLangOpts().MicrosoftExt
12093 ? diag::ext_flexible_array_union_ms
12094 : getLangOpts().CPlusPlus
12095 ? diag::ext_flexible_array_union_gnu
12096 : diag::err_flexible_array_union;
12097 else if (Fields.size() == 1)
12098 DiagID = getLangOpts().MicrosoftExt
12099 ? diag::ext_flexible_array_empty_aggregate_ms
12100 : getLangOpts().CPlusPlus
12101 ? diag::ext_flexible_array_empty_aggregate_gnu
12102 : NumNamedMembers < 1
12103 ? diag::err_flexible_array_empty_aggregate
12104 : 0;
12105
12106 if (DiagID)
12107 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12108 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000012109 // While the layout of types that contain virtual bases is not specified
12110 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12111 // virtual bases after the derived members. This would make a flexible
12112 // array member declared at the end of an object not adjacent to the end
12113 // of the type.
12114 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12115 if (RD->getNumVBases() != 0)
12116 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12117 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000012118 if (!getLangOpts().C99)
12119 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12120 << FD->getDeclName() << Record->getTagKind();
12121
Richard Smith6fa28ff2014-01-11 00:53:35 +000012122 // If the element type has a non-trivial destructor, we would not
12123 // implicitly destroy the elements, so disallow it for now.
12124 //
12125 // FIXME: GCC allows this. We should probably either implicitly delete
12126 // the destructor of the containing class, or just allow this.
12127 QualType BaseElem = Context.getBaseElementType(FD->getType());
12128 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12129 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000012130 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000012131 FD->setInvalidDecl();
12132 EnclosingDecl->setInvalidDecl();
12133 continue;
12134 }
Chris Lattner720a0542007-01-25 00:44:24 +000012135 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000012136 if (Record)
12137 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000012138 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000012139 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000012140 diag::err_field_incomplete)) {
12141 // Incomplete type
12142 FD->setInvalidDecl();
12143 EnclosingDecl->setInvalidDecl();
12144 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012145 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000012146 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12147 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012148 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012149 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012150 } else {
12151 // If this is a struct/class and this is not the last element, reject
12152 // it. Note that GCC supports variable sized arrays in the middle of
12153 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012154 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012155 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012156 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012157 else {
12158 // We support flexible arrays at the end of structs in
12159 // other structs as an extension.
12160 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12161 << FD->getDeclName();
12162 if (Record)
12163 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012164 }
Chris Lattner720a0542007-01-25 00:44:24 +000012165 }
12166 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012167 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12168 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12169 diag::err_abstract_type_in_decl,
12170 AbstractIvarType)) {
12171 // Ivars can not have abstract class types
12172 FD->setInvalidDecl();
12173 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012174 if (Record && FDTTy->getDecl()->hasObjectMember())
12175 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012176 if (Record && FDTTy->getDecl()->hasVolatileMember())
12177 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012178 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012179 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012180 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12181 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12182 QualType T = Context.getObjCObjectPointerType(FD->getType());
12183 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012184 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12185 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12186 // It's an error in ARC if a field has lifetime.
12187 // We don't want to report this in a system header, though,
12188 // so we just make the field unavailable.
12189 // FIXME: that's really not sufficient; we need to make the type
12190 // itself invalid to, say, initialize or copy.
12191 QualType T = FD->getType();
12192 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12193 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12194 SourceLocation loc = FD->getLocation();
12195 if (getSourceManager().isInSystemHeader(loc)) {
12196 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012197 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12198 "this system field has retaining ownership",
12199 loc));
John McCall31168b02011-06-15 23:02:42 +000012200 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012201 } else {
12202 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012203 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012204 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012205 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012206 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012207 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012208 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012209 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012210 if (FD->getType()->isObjCObjectPointerType() ||
12211 FD->getType().isObjCGCStrong())
12212 Record->setHasObjectMember(true);
12213 else if (Context.getAsArrayType(FD->getType())) {
12214 QualType BaseType = Context.getBaseElementType(FD->getType());
12215 if (BaseType->isRecordType() &&
12216 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012217 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012218 else if (BaseType->isObjCObjectPointerType() ||
12219 BaseType.isObjCGCStrong())
12220 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012221 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012222 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012223 if (Record && FD->getType().isVolatileQualified())
12224 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012225 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012226 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012227 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012228 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012229
Chris Lattner82625602007-01-24 02:26:21 +000012230 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012231 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012232 bool Completed = false;
12233 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12234 if (!CXXRecord->isInvalidDecl()) {
12235 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012236 for (CXXRecordDecl::conversion_iterator
12237 I = CXXRecord->conversion_begin(),
12238 E = CXXRecord->conversion_end(); I != E; ++I)
12239 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012240
12241 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012242 if (CXXRecord->hasUserDeclaredDestructor()) {
12243 // Adjust user-defined destructor exception spec.
12244 if (getLangOpts().CPlusPlus11)
12245 AdjustDestructorExceptionSpec(CXXRecord,
12246 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012247 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012248
Douglas Gregor8fb95122010-09-29 00:15:42 +000012249 // Add any implicitly-declared members to this class.
12250 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12251
12252 // If we have virtual base classes, we may end up finding multiple
12253 // final overriders for a given virtual function. Check for this
12254 // problem now.
12255 if (CXXRecord->getNumVBases()) {
12256 CXXFinalOverriderMap FinalOverriders;
12257 CXXRecord->getFinalOverriders(FinalOverriders);
12258
12259 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12260 MEnd = FinalOverriders.end();
12261 M != MEnd; ++M) {
12262 for (OverridingMethods::iterator SO = M->second.begin(),
12263 SOEnd = M->second.end();
12264 SO != SOEnd; ++SO) {
12265 assert(SO->second.size() > 0 &&
12266 "Virtual function without overridding functions?");
12267 if (SO->second.size() == 1)
12268 continue;
12269
12270 // C++ [class.virtual]p2:
12271 // In a derived class, if a virtual member function of a base
12272 // class subobject has more than one final overrider the
12273 // program is ill-formed.
12274 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012275 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012276 Diag(M->first->getLocation(),
12277 diag::note_overridden_virtual_function);
12278 for (OverridingMethods::overriding_iterator
12279 OM = SO->second.begin(),
12280 OMEnd = SO->second.end();
12281 OM != OMEnd; ++OM)
12282 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012283 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012284
12285 Record->setInvalidDecl();
12286 }
12287 }
12288 CXXRecord->completeDefinition(&FinalOverriders);
12289 Completed = true;
12290 }
12291 }
12292 }
12293 }
12294
12295 if (!Completed)
12296 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012297
David Majnemer2c4e00a2014-01-29 22:07:36 +000012298 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012299 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012300
David Majnemer98c9ee22014-02-07 00:43:07 +000012301 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012302 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012303 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012304 IA->getSemanticSpelling());
12305 }
12306
Serge Pavlov3cb80222013-11-14 02:13:03 +000012307 // Check if the structure/union declaration is a type that can have zero
12308 // size in C. For C this is a language extension, for C++ it may cause
12309 // compatibility problems.
12310 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012311 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012312 CheckForZeroSize = true;
12313 } else {
12314 // For C++ filter out types that cannot be referenced in C code.
12315 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12316 CheckForZeroSize =
12317 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12318 !CXXRecord->isDependentType() &&
12319 CXXRecord->isCLike();
12320 }
12321 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012322 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012323 bool IsEmpty = true;
12324 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012325 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012326 E = Record->field_end();
12327 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12328 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012329 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012330 if (I->getBitWidthValue(Context) > 0)
12331 ZeroSize = false;
12332 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012333 ++NonBitFields;
12334 QualType FieldType = I->getType();
12335 if (FieldType->isIncompleteType() ||
12336 !Context.getTypeSizeInChars(FieldType).isZero())
12337 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012338 }
12339 }
12340
Serge Pavlov3cb80222013-11-14 02:13:03 +000012341 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12342 // allowed in C++, but warn if its declaration is inside
12343 // extern "C" block.
12344 if (ZeroSize) {
12345 Diag(RecLoc, getLangOpts().CPlusPlus ?
12346 diag::warn_zero_size_struct_union_in_extern_c :
12347 diag::warn_zero_size_struct_union_compat)
12348 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12349 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012350
Serge Pavlov3cb80222013-11-14 02:13:03 +000012351 // Structs without named members are extension in C (C99 6.7.2.1p7),
12352 // but are accepted by GCC.
12353 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12354 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12355 diag::ext_no_named_members_in_struct_union)
12356 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012357 }
12358 }
Chris Lattner622c1932008-02-06 00:51:33 +000012359 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012360 ObjCIvarDecl **ClsFields =
12361 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012362 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012363 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012364 // Add ivar's to class's DeclContext.
12365 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12366 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012367 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012368 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012369 // Must enforce the rule that ivars in the base classes may not be
12370 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012371 if (ID->getSuperClass())
12372 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012373 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012374 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012375 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012376 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12377 // Ivar declared in @implementation never belongs to the implementation.
12378 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012379 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012380 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012381 IMPDecl->setIvarLBraceLoc(LBrac);
12382 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012383 } else if (ObjCCategoryDecl *CDecl =
12384 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012385 // case of ivars in class extension; all other cases have been
12386 // reported as errors elsewhere.
12387 // FIXME. Class extension does not have a LocEnd field.
12388 // CDecl->setLocEnd(RBrac);
12389 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012390 // Diagnose redeclaration of private ivars.
12391 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012392 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012393 if (IDecl) {
12394 if (const ObjCIvarDecl *ClsIvar =
12395 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12396 Diag(ClsFields[i]->getLocation(),
12397 diag::err_duplicate_ivar_declaration);
12398 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12399 continue;
12400 }
Aaron Ballmanb4a53452014-03-13 21:57:01 +000012401 for (const auto *Ext : IDecl->known_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012402 if (const ObjCIvarDecl *ClsExtIvar
12403 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012404 Diag(ClsFields[i]->getLocation(),
12405 diag::err_duplicate_ivar_declaration);
12406 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12407 continue;
12408 }
12409 }
12410 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012411 ClsFields[i]->setLexicalDeclContext(CDecl);
12412 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012413 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012414 CDecl->setIvarLBraceLoc(LBrac);
12415 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012416 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012417 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012418
12419 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012420 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012421}
12422
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012423/// \brief Determine whether the given integral value is representable within
12424/// the given type T.
12425static bool isRepresentableIntegerValue(ASTContext &Context,
12426 llvm::APSInt &Value,
12427 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012428 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012429 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012430
Douglas Gregor0bf31402010-10-08 23:50:27 +000012431 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012432 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012433 --BitWidth;
12434 return Value.getActiveBits() <= BitWidth;
12435 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012436 return Value.getMinSignedBits() <= BitWidth;
12437}
12438
12439// \brief Given an integral type, return the next larger integral type
12440// (or a NULL type of no such type exists).
12441static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12442 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12443 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012444 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012445 const unsigned NumTypes = 4;
12446 QualType SignedIntegralTypes[NumTypes] = {
12447 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12448 };
12449 QualType UnsignedIntegralTypes[NumTypes] = {
12450 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12451 Context.UnsignedLongLongTy
12452 };
12453
12454 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012455 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12456 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012457 for (unsigned I = 0; I != NumTypes; ++I)
12458 if (Context.getTypeSize(Types[I]) > BitWidth)
12459 return Types[I];
12460
12461 return QualType();
12462}
12463
Douglas Gregor954f6b272009-03-17 19:05:46 +000012464EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12465 EnumConstantDecl *LastEnumConst,
12466 SourceLocation IdLoc,
12467 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012468 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012469 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012470 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012471 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012472
12473 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12474 Val = 0;
12475
Eli Friedman7c6515a2011-12-06 00:10:34 +000012476 if (Val)
12477 Val = DefaultLvalueConversion(Val).take();
12478
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012479 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012480 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012481 EltTy = Context.DependentTy;
12482 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012483 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012484 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012485 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012486 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12487 // constant-expression in the enumerator-definition shall be a converted
12488 // constant expression of the underlying type.
12489 EltTy = Enum->getIntegerType();
12490 ExprResult Converted =
12491 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12492 CCEK_Enumerator);
12493 if (Converted.isInvalid())
12494 Val = 0;
12495 else
12496 Val = Converted.take();
12497 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012498 !(Val = VerifyIntegerConstantExpression(Val,
12499 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012500 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012501 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012502 if (Enum->isFixed()) {
12503 EltTy = Enum->getIntegerType();
12504
Richard Smithf8379a02012-01-18 23:55:52 +000012505 // In Obj-C and Microsoft mode, require the enumeration value to be
12506 // representable in the underlying type of the enumeration. In C++11,
12507 // we perform a non-narrowing conversion as part of converted constant
12508 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012509 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012510 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012511 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012512 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012513 } else
12514 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012515 } else
John Wiegley01296292011-04-08 18:41:53 +000012516 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012517 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012518 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012519 // If the underlying type is not fixed, the type of each enumerator
12520 // is the type of its initializing value:
12521 // - If an initializer is specified for an enumerator, the
12522 // initializing value has the same type as the expression.
12523 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012524 } else {
12525 // C99 6.7.2.2p2:
12526 // The expression that defines the value of an enumeration constant
12527 // shall be an integer constant expression that has a value
12528 // representable as an int.
12529
12530 // Complain if the value is not representable in an int.
12531 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12532 Diag(IdLoc, diag::ext_enum_value_not_int)
12533 << EnumVal.toString(10) << Val->getSourceRange()
12534 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12535 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12536 // Force the type of the expression to 'int'.
12537 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12538 }
12539 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012540 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012541 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012542 }
12543 }
Mike Stump11289f42009-09-09 15:08:12 +000012544
Douglas Gregor954f6b272009-03-17 19:05:46 +000012545 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012546 if (Enum->isDependentType())
12547 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012548 else if (!LastEnumConst) {
12549 // C++0x [dcl.enum]p5:
12550 // If the underlying type is not fixed, the type of each enumerator
12551 // is the type of its initializing value:
12552 // - If no initializer is specified for the first enumerator, the
12553 // initializing value has an unspecified integral type.
12554 //
12555 // GCC uses 'int' for its unspecified integral type, as does
12556 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012557 if (Enum->isFixed()) {
12558 EltTy = Enum->getIntegerType();
12559 }
12560 else {
12561 EltTy = Context.IntTy;
12562 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012563 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012564 // Assign the last value + 1.
12565 EnumVal = LastEnumConst->getInitVal();
12566 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012567 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012568
12569 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012570 if (EnumVal < LastEnumConst->getInitVal()) {
12571 // C++0x [dcl.enum]p5:
12572 // If the underlying type is not fixed, the type of each enumerator
12573 // is the type of its initializing value:
12574 //
12575 // - Otherwise the type of the initializing value is the same as
12576 // the type of the initializing value of the preceding enumerator
12577 // unless the incremented value is not representable in that type,
12578 // in which case the type is an unspecified integral type
12579 // sufficient to contain the incremented value. If no such type
12580 // exists, the program is ill-formed.
12581 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012582 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012583 // There is no integral type larger enough to represent this
12584 // value. Complain, then allow the value to wrap around.
12585 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012586 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012587 ++EnumVal;
12588 if (Enum->isFixed())
12589 // When the underlying type is fixed, this is ill-formed.
12590 Diag(IdLoc, diag::err_enumerator_wrapped)
12591 << EnumVal.toString(10)
12592 << EltTy;
12593 else
Richard Smithfaf156a2014-03-05 22:54:58 +000012594 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000012595 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012596 } else {
12597 EltTy = T;
12598 }
12599
12600 // Retrieve the last enumerator's value, extent that type to the
12601 // type that is supposed to be large enough to represent the incremented
12602 // value, then increment.
12603 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012604 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012605 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012606 ++EnumVal;
12607
12608 // If we're not in C++, diagnose the overflow of enumerator values,
12609 // which in C99 means that the enumerator value is not representable in
12610 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12611 // permits enumerator values that are representable in some larger
12612 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012613 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012614 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012615 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012616 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12617 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12618 Diag(IdLoc, diag::ext_enum_value_not_int)
12619 << EnumVal.toString(10) << 1;
12620 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012621 }
12622 }
Mike Stump11289f42009-09-09 15:08:12 +000012623
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012624 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012625 // Make the enumerator value match the signedness and size of the
12626 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012627 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012628 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012629 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012630
Douglas Gregor954f6b272009-03-17 19:05:46 +000012631 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012632 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012633}
12634
12635
John McCall811a0f52010-10-22 23:36:17 +000012636Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12637 SourceLocation IdLoc, IdentifierInfo *Id,
12638 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012639 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012640 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012641 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012642 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012643
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012644 // The scope passed in may not be a decl scope. Zip up the scope tree until
12645 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012646 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012647
Chris Lattner8116d1b2007-01-25 22:38:29 +000012648 // Verify that there isn't already something declared with this name in this
12649 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012650 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012651 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012652 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012653 // Maybe we will complain about the shadowed template parameter.
12654 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12655 // Just pretend that we didn't see the previous declaration.
12656 PrevDecl = 0;
12657 }
12658
12659 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012660 // When in C++, we may get a TagDecl with the same name; in this case the
12661 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012662 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012663 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012664 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012665 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012666 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012667 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012668 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012669 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012670 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012671 }
12672 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012673
Aaron Ballman24a10472012-07-19 03:12:23 +000012674 // C++ [class.mem]p15:
12675 // If T is the name of a class, then each of the following shall have a name
12676 // different from T:
12677 // - every enumerator of every member of class T that is an unscoped
12678 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012679 if (CXXRecordDecl *Record
12680 = dyn_cast<CXXRecordDecl>(
12681 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012682 if (!TheEnumDecl->isScoped() &&
12683 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012684 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12685
John McCall811a0f52010-10-22 23:36:17 +000012686 EnumConstantDecl *New =
12687 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012688
John McCall553c0792010-01-23 00:46:32 +000012689 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012690 // Process attributes.
12691 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12692
12693 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012694 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012695 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012696 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012697
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012698 ActOnDocumentableDecl(New);
12699
John McCall48871652010-08-21 09:40:31 +000012700 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012701}
12702
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012703// Returns true when the enum initial expression does not trigger the
12704// duplicate enum warning. A few common cases are exempted as follows:
12705// Element2 = Element1
12706// Element2 = Element1 + 1
12707// Element2 = Element1 - 1
12708// Where Element2 and Element1 are from the same enum.
12709static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12710 Expr *InitExpr = ECD->getInitExpr();
12711 if (!InitExpr)
12712 return true;
12713 InitExpr = InitExpr->IgnoreImpCasts();
12714
12715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12716 if (!BO->isAdditiveOp())
12717 return true;
12718 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12719 if (!IL)
12720 return true;
12721 if (IL->getValue() != 1)
12722 return true;
12723
12724 InitExpr = BO->getLHS();
12725 }
12726
12727 // This checks if the elements are from the same enum.
12728 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12729 if (!DRE)
12730 return true;
12731
12732 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12733 if (!EnumConstant)
12734 return true;
12735
12736 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12737 Enum)
12738 return true;
12739
12740 return false;
12741}
12742
12743struct DupKey {
12744 int64_t val;
12745 bool isTombstoneOrEmptyKey;
12746 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12747 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12748};
12749
12750static DupKey GetDupKey(const llvm::APSInt& Val) {
12751 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12752 false);
12753}
12754
12755struct DenseMapInfoDupKey {
12756 static DupKey getEmptyKey() { return DupKey(0, true); }
12757 static DupKey getTombstoneKey() { return DupKey(1, true); }
12758 static unsigned getHashValue(const DupKey Key) {
12759 return (unsigned)(Key.val * 37);
12760 }
12761 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12762 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12763 LHS.val == RHS.val;
12764 }
12765};
12766
12767// Emits a warning when an element is implicitly set a value that
12768// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012769static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12770 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012771 QualType EnumType) {
12772 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12773 Enum->getLocation()) ==
12774 DiagnosticsEngine::Ignored)
12775 return;
12776 // Avoid anonymous enums
12777 if (!Enum->getIdentifier())
12778 return;
12779
12780 // Only check for small enums.
12781 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12782 return;
12783
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012784 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12785 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012786
12787 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12788 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12789 ValueToVectorMap;
12790
12791 DuplicatesVector DupVector;
12792 ValueToVectorMap EnumMap;
12793
12794 // Populate the EnumMap with all values represented by enum constants without
12795 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012796 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012797 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012798
12799 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12800 // this constant. Skip this enum since it may be ill-formed.
12801 if (!ECD) {
12802 return;
12803 }
12804
12805 if (ECD->getInitExpr())
12806 continue;
12807
12808 DupKey Key = GetDupKey(ECD->getInitVal());
12809 DeclOrVector &Entry = EnumMap[Key];
12810
12811 // First time encountering this value.
12812 if (Entry.isNull())
12813 Entry = ECD;
12814 }
12815
12816 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012817 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012818 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12819 if (!ValidDuplicateEnum(ECD, Enum))
12820 continue;
12821
12822 DupKey Key = GetDupKey(ECD->getInitVal());
12823
12824 DeclOrVector& Entry = EnumMap[Key];
12825 if (Entry.isNull())
12826 continue;
12827
12828 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12829 // Ensure constants are different.
12830 if (D == ECD)
12831 continue;
12832
12833 // Create new vector and push values onto it.
12834 ECDVector *Vec = new ECDVector();
12835 Vec->push_back(D);
12836 Vec->push_back(ECD);
12837
12838 // Update entry to point to the duplicates vector.
12839 Entry = Vec;
12840
12841 // Store the vector somewhere we can consult later for quick emission of
12842 // diagnostics.
12843 DupVector.push_back(Vec);
12844 continue;
12845 }
12846
12847 ECDVector *Vec = Entry.get<ECDVector*>();
12848 // Make sure constants are not added more than once.
12849 if (*Vec->begin() == ECD)
12850 continue;
12851
12852 Vec->push_back(ECD);
12853 }
12854
12855 // Emit diagnostics.
12856 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12857 DupVectorEnd = DupVector.end();
12858 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12859 ECDVector *Vec = *DupVectorIter;
12860 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12861
12862 // Emit warning for one enum constant.
12863 ECDVector::iterator I = Vec->begin();
12864 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12865 << (*I)->getName() << (*I)->getInitVal().toString(10)
12866 << (*I)->getSourceRange();
12867 ++I;
12868
12869 // Emit one note for each of the remaining enum constants with
12870 // the same value.
12871 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12872 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12873 << (*I)->getName() << (*I)->getInitVal().toString(10)
12874 << (*I)->getSourceRange();
12875 delete Vec;
12876 }
12877}
12878
Mike Stump6814d1c2009-05-16 07:06:02 +000012879void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012880 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012881 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012882 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012883 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012884 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012885
12886 if (Attr)
12887 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012888
Eli Friedmand0e60972009-12-11 01:34:50 +000012889 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012890 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012891 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012892 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012893 if (!ECD) continue;
12894
12895 ECD->setType(EnumType);
12896 }
12897
John McCall9aa35be2010-05-06 08:49:23 +000012898 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012899 return;
12900 }
12901
Chris Lattner67933c02007-08-28 05:10:31 +000012902 // TODO: If the result value doesn't fit in an int, it must be a long or long
12903 // long value. ISO C does not support this, but GCC does as an extension,
12904 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012905 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12906 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12907 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012908
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012909 // Verify that all the values are okay, compute the size of the values, and
12910 // reverse the list.
12911 unsigned NumNegativeBits = 0;
12912 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012913
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012914 // Keep track of whether all elements have type int.
12915 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012916
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012917 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012918 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012919 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012920 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012921
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012922 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012923
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012924 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012925 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012926 NumPositiveBits = std::max(NumPositiveBits,
12927 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012928 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012929 NumNegativeBits = std::max(NumNegativeBits,
12930 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012931
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012932 // Keep track of whether every enum element has type int (very commmon).
12933 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012934 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012935 }
Mike Stump11289f42009-09-09 15:08:12 +000012936
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012937 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012938 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012939 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012940
John McCall56774992009-12-09 09:09:27 +000012941 // C++0x N3000 [conv.prom]p3:
12942 // An rvalue of an unscoped enumeration type whose underlying
12943 // type is not fixed can be converted to an rvalue of the first
12944 // of the following types that can represent all the values of
12945 // the enumeration: int, unsigned int, long int, unsigned long
12946 // int, long long int, or unsigned long long int.
12947 // C99 6.4.4.3p2:
12948 // An identifier declared as an enumeration constant has type int.
12949 // The C99 rule is modified by a gcc extension
12950 QualType BestPromotionType;
12951
Aaron Ballman9ead1242013-12-19 02:39:40 +000012952 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012953 // -fshort-enums is the equivalent to specifying the packed attribute on all
12954 // enum definitions.
12955 if (LangOpts.ShortEnums)
12956 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012957
Douglas Gregor0bf31402010-10-08 23:50:27 +000012958 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012959 BestType = Enum->getIntegerType();
12960 if (BestType->isPromotableIntegerType())
12961 BestPromotionType = Context.getPromotedIntegerType(BestType);
12962 else
12963 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012964 // We don't need to set BestWidth, because BestType is going to be the type
12965 // of the enumerators, but we do anyway because otherwise some compilers
12966 // warn that it might be used uninitialized.
12967 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012968 }
12969 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012970 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012971 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012972 // If it's packed, check also if it fits a char or a short.
12973 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012974 BestType = Context.SignedCharTy;
12975 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012976 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012977 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012978 BestType = Context.ShortTy;
12979 BestWidth = ShortWidth;
12980 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012981 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012982 BestWidth = IntWidth;
12983 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012984 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012985
John McCall56774992009-12-09 09:09:27 +000012986 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012987 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012988 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012989 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012990
Chris Lattner3a370bf2007-08-29 17:31:48 +000012991 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000012992 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012993 BestType = Context.LongLongTy;
12994 }
12995 }
John McCall56774992009-12-09 09:09:27 +000012996 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012997 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012998 // If there is no negative value, figure out the smallest type that fits
12999 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013000 // If it's packed, check also if it fits a char or a short.
13001 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013002 BestType = Context.UnsignedCharTy;
13003 BestPromotionType = Context.IntTy;
13004 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013005 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013006 BestType = Context.UnsignedShortTy;
13007 BestPromotionType = Context.IntTy;
13008 BestWidth = ShortWidth;
13009 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013010 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013011 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000013012 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013013 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013014 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013015 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000013016 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013017 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013018 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013019 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013020 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000013021 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013022 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013023 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013024 "How could an initializer get larger than ULL?");
13025 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013026 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013027 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013028 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013029 }
13030 }
Mike Stump11289f42009-09-09 15:08:12 +000013031
Chris Lattner3a370bf2007-08-29 17:31:48 +000013032 // Loop over all of the enumerator constants, changing their types to match
13033 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013034 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000013035 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013036 if (!ECD) continue; // Already issued a diagnostic.
13037
13038 // Standard C says the enumerators have int type, but we allow, as an
13039 // extension, the enumerators to be larger than int size. If each
13040 // enumerator value fits in an int, type it as an int, otherwise type it the
13041 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
13042 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000013043
13044 // Determine whether the value fits into an int.
13045 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013046
13047 // If it fits into an integer type, force it. Otherwise force it to match
13048 // the enum decl type.
13049 QualType NewTy;
13050 unsigned NewWidth;
13051 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000013052 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000013053 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013054 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000013055 NewTy = Context.IntTy;
13056 NewWidth = IntWidth;
13057 NewSign = true;
13058 } else if (ECD->getType() == BestType) {
13059 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000013060 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013061 // C++ [dcl.enum]p4: Following the closing brace of an
13062 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013063 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013064 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013065 continue;
13066 } else {
13067 NewTy = BestType;
13068 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013069 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013070 }
13071
13072 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000013073 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013074 InitVal.setIsSigned(NewSign);
13075 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000013076
Chris Lattner3a370bf2007-08-29 17:31:48 +000013077 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000013078 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000013079 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000013080 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000013081 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000013082 ECD->getInitExpr(),
13083 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000013084 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000013085 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013086 // C++ [dcl.enum]p4: Following the closing brace of an
13087 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013088 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013089 ECD->setType(EnumType);
13090 else
13091 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013092 }
Mike Stump11289f42009-09-09 15:08:12 +000013093
John McCall9aa35be2010-05-06 08:49:23 +000013094 Enum->completeDefinition(BestType, BestPromotionType,
13095 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000013096
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013097 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000013098
13099 // Now that the enum type is defined, ensure it's not been underaligned.
13100 if (Enum->hasAttrs())
13101 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013102}
Chris Lattner1300fb92007-01-23 23:42:53 +000013103
Abramo Bagnara348823a2011-03-03 14:20:18 +000013104Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13105 SourceLocation StartLoc,
13106 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000013107 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000013108
Douglas Gregor278f52e2009-05-30 00:08:05 +000013109 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000013110 AsmString, StartLoc,
13111 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013112 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000013113 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000013114}
Eli Friedman5ed51982009-06-05 02:44:36 +000013115
Richard Smith77944862014-03-02 05:58:18 +000013116static void checkModuleImportContext(Sema &S, Module *M,
13117 SourceLocation ImportLoc,
13118 DeclContext *DC) {
13119 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13120 switch (LSD->getLanguage()) {
13121 case LinkageSpecDecl::lang_c:
13122 if (!M->IsExternC) {
13123 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13124 << M->getFullModuleName();
13125 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13126 return;
13127 }
13128 break;
13129 case LinkageSpecDecl::lang_cxx:
13130 break;
13131 }
13132 DC = LSD->getParent();
13133 }
13134
13135 while (isa<LinkageSpecDecl>(DC))
13136 DC = DC->getParent();
13137 if (!isa<TranslationUnitDecl>(DC)) {
13138 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13139 << M->getFullModuleName() << DC;
13140 S.Diag(cast<Decl>(DC)->getLocStart(),
13141 diag::note_module_import_not_at_top_level)
13142 << DC;
13143 }
13144}
13145
Douglas Gregor22d09742012-01-03 18:04:46 +000013146DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13147 SourceLocation ImportLoc,
13148 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000013149 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000013150 Module::AllVisible,
13151 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013152 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013153 return true;
Richard Smith77944862014-03-02 05:58:18 +000013154
13155 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13156
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013157 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013158 Module *ModCheck = Mod;
13159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13160 // If we've run out of module parents, just drop the remaining identifiers.
13161 // We need the length to be consistent.
13162 if (!ModCheck)
13163 break;
13164 ModCheck = ModCheck->Parent;
13165
13166 IdentifierLocs.push_back(Path[I].second);
13167 }
13168
13169 ImportDecl *Import = ImportDecl::Create(Context,
13170 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013171 AtLoc.isValid()? AtLoc : ImportLoc,
13172 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013173 Context.getTranslationUnitDecl()->addDecl(Import);
13174 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013175}
13176
Richard Smithce587f52013-11-15 04:24:58 +000013177void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013178 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13179
Richard Smithce587f52013-11-15 04:24:58 +000013180 // FIXME: Should we synthesize an ImportDecl here?
13181 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13182 /*Complain=*/true);
13183}
13184
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013185void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13186 // Create the implicit import declaration.
13187 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13188 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13189 Loc, Mod, Loc);
13190 TU->addDecl(ImportD);
13191 Consumer.HandleImplicitImportDecl(ImportD);
13192
13193 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000013194 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13195 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013196}
13197
David Chisnall0867d9c2012-02-18 16:12:34 +000013198void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13199 IdentifierInfo* AliasName,
13200 SourceLocation PragmaLoc,
13201 SourceLocation NameLoc,
13202 SourceLocation AliasNameLoc) {
13203 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13204 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013205 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13206 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013207
13208 if (PrevDecl)
13209 PrevDecl->addAttr(Attr);
13210 else
13211 (void)ExtnameUndeclaredIdentifiers.insert(
13212 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13213}
13214
Eli Friedman5ed51982009-06-05 02:44:36 +000013215void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13216 SourceLocation PragmaLoc,
13217 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013218 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013219
Eli Friedman5ed51982009-06-05 02:44:36 +000013220 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013221 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013222 } else {
13223 (void)WeakUndeclaredIdentifiers.insert(
13224 std::pair<IdentifierInfo*,WeakInfo>
13225 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013226 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013227}
13228
13229void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13230 IdentifierInfo* AliasName,
13231 SourceLocation PragmaLoc,
13232 SourceLocation NameLoc,
13233 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013234 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13235 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013236 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013237
Eli Friedman5ed51982009-06-05 02:44:36 +000013238 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013239 if (!PrevDecl->hasAttr<AliasAttr>())
13240 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013241 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013242 } else {
13243 (void)WeakUndeclaredIdentifiers.insert(
13244 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013245 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013246}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013247
13248Decl *Sema::getObjCDeclContext() const {
13249 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13250}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013251
13252AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013253 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013254 // If we are within an Objective-C method, we should consult
13255 // both the availability of the method as well as the
13256 // enclosing class. If the class is (say) deprecated,
13257 // the entire method is considered deprecated from the
13258 // purpose of checking if the current context is deprecated.
13259 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13260 AvailabilityResult R = MD->getAvailability();
13261 if (R != AR_Available)
13262 return R;
13263 D = MD->getClassInterface();
13264 }
13265 // If we are within an Objective-c @implementation, it
13266 // gets the same availability context as the @interface.
13267 else if (const ObjCImplementationDecl *ID =
13268 dyn_cast<ObjCImplementationDecl>(D)) {
13269 D = ID->getClassInterface();
13270 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013271 return D->getAvailability();
13272}