blob: fa51aa4c09fd5b2b599915411506145e28de38e6 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregor9e876872011-03-01 18:12:44 +000015#include "TypeLocBuilder.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000020#include "clang/AST/CommentDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Chandler Carrutha7689ef2011-03-27 09:46:56 +000024#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000025#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000026#include "clang/AST/StmtCXX.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
31#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
32#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
33#include "clang/Parse/ParseDiagnostic.h"
34#include "clang/Sema/CXXFieldCollector.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/DelayedDiagnostic.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000042#include "llvm/ADT/SmallString.h"
John McCall66755862009-12-24 09:58:38 +000043#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000044#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000045#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000046#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000047using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000048using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Richard Smithc89edf52011-07-01 19:46:12 +000050Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51 if (OwnedType) {
52 Decl *Group[2] = { OwnedType, Ptr };
53 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54 }
55
John McCalld226f652010-08-21 09:40:31 +000056 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner682bf922009-03-29 16:50:03 +000057}
58
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000059namespace {
60
61class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62 public:
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000063 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
64 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000065 WantExpressionKeywords = false;
66 WantCXXNamedCasts = false;
67 WantRemainingKeywords = false;
68 }
69
70 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
71 if (NamedDecl *ND = candidate.getCorrectionDecl())
72 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
73 (AllowInvalidDecl || !ND->isInvalidDecl());
74 else
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000075 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000076 }
77
78 private:
79 bool AllowInvalidDecl;
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000080 bool WantClassName;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000081};
82
83}
84
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +000085/// \brief Determine whether the token kind starts a simple-type-specifier.
86bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
87 switch (Kind) {
88 // FIXME: Take into account the current language when deciding whether a
89 // token kind is a valid type specifier
90 case tok::kw_short:
91 case tok::kw_long:
92 case tok::kw___int64:
93 case tok::kw___int128:
94 case tok::kw_signed:
95 case tok::kw_unsigned:
96 case tok::kw_void:
97 case tok::kw_char:
98 case tok::kw_int:
99 case tok::kw_half:
100 case tok::kw_float:
101 case tok::kw_double:
102 case tok::kw_wchar_t:
103 case tok::kw_bool:
104 case tok::kw___underlying_type:
105 return true;
106
107 case tok::annot_typename:
108 case tok::kw_char16_t:
109 case tok::kw_char32_t:
110 case tok::kw_typeof:
David Majnemerff989a82013-09-22 01:24:26 +0000111 case tok::annot_decltype:
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +0000112 case tok::kw_decltype:
113 return getLangOpts().CPlusPlus;
114
115 default:
116 break;
117 }
118
119 return false;
120}
121
Douglas Gregord6efafa2009-02-04 19:16:12 +0000122/// \brief If the identifier refers to a type name within this scope,
123/// return the declaration of that type.
124///
125/// This routine performs ordinary name lookup of the identifier II
126/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000127/// determine whether the name refers to a type. If so, returns an
128/// opaque pointer (actually a QualType) corresponding to that
129/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +0000130///
131/// If name lookup results in an ambiguity, this routine will complain
132/// and then return NULL.
Dmitri Gribenko8eead162013-05-03 13:12:11 +0000133ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallb3d87482010-08-24 05:47:05 +0000134 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000135 bool isClassName, bool HasTrailingDot,
Douglas Gregor9e876872011-03-01 18:12:44 +0000136 ParsedType ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000137 bool IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000138 bool WantNontrivialTypeSourceInfo,
139 IdentifierInfo **CorrectedII) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000140 // Determine where we will perform name lookup.
141 DeclContext *LookupCtx = 0;
142 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +0000143 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000144 if (ObjectType->isRecordType())
145 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +0000146 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000147 LookupCtx = computeDeclContext(*SS, false);
148
149 if (!LookupCtx) {
150 if (isDependentScopeSpecifier(*SS)) {
151 // C++ [temp.res]p3:
152 // A qualified-id that refers to a type and in which the
153 // nested-name-specifier depends on a template-parameter (14.6.2)
154 // shall be prefixed by the keyword typename to indicate that the
155 // qualified-id denotes a type, forming an
156 // elaborated-type-specifier (7.1.5.3).
157 //
158 // We therefore do not perform any name lookup if the result would
159 // refer to a member of an unknown specialization.
Richard Smithc5a89a12012-04-02 01:30:27 +0000160 if (!isClassName && !IsCtorOrDtorName)
John McCallb3d87482010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000162
John McCall33500952010-06-11 00:33:02 +0000163 // We know from the grammar that this name refers to a type,
164 // so build a dependent node to describe the type.
Douglas Gregor9e876872011-03-01 18:12:44 +0000165 if (WantNontrivialTypeSourceInfo)
166 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
167
168 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallb3d87482010-08-24 05:47:05 +0000169 QualType T =
Douglas Gregor9e876872011-03-01 18:12:44 +0000170 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +0000171 II, NameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +0000172
173 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000174 }
175
John McCallb3d87482010-08-24 05:47:05 +0000176 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000177 }
178
John McCall77bb1aa2010-05-01 00:40:08 +0000179 if (!LookupCtx->isDependentContext() &&
180 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000181 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000182 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000183
184 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
185 // lookup for class-names.
186 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
187 LookupOrdinaryName;
188 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000189 if (LookupCtx) {
190 // Perform "qualified" name lookup into the declaration context we
191 // computed, which is either the type of the base of a member access
192 // expression or the declaration context associated with a prior
193 // nested-name-specifier.
194 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000195
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000196 if (ObjectTypePtr && Result.empty()) {
197 // C++ [basic.lookup.classref]p3:
198 // If the unqualified-id is ~type-name, the type-name is looked up
199 // in the context of the entire postfix-expression. If the type T of
200 // the object expression is of a class type C, the type-name is also
201 // looked up in the scope of class C. At least one of the lookups shall
202 // find a name that refers to (possibly cv-qualified) T.
203 LookupName(Result, S);
204 }
205 } else {
206 // Perform unqualified name lookup.
207 LookupName(Result, S);
208 }
209
Chris Lattner22bd9052009-02-16 22:07:16 +0000210 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000211 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000212 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000213 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000214 if (CorrectedII) {
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +0000215 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000216 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000217 Kind, S, SS, Validator);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000218 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
219 TemplateTy Template;
220 bool MemberOfUnknownSpecialization;
221 UnqualifiedId TemplateName;
222 TemplateName.setIdentifier(NewII, NameLoc);
223 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
224 CXXScopeSpec NewSS, *NewSSPtr = SS;
225 if (SS && NNS) {
226 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
227 NewSSPtr = &NewSS;
228 }
229 if (Correction && (NNS || NewII != &II) &&
230 // Ignore a correction to a template type as the to-be-corrected
231 // identifier is not a template (typo correction for template names
232 // is handled elsewhere).
David Blaikie4e4d0842012-03-11 07:00:24 +0000233 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000234 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
235 false, Template, MemberOfUnknownSpecialization))) {
236 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
237 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000238 IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000239 WantNontrivialTypeSourceInfo);
240 if (Ty) {
Richard Smith2d670972013-08-17 00:46:16 +0000241 diagnoseTypo(Correction,
242 PDiag(diag::err_unknown_type_or_class_name_suggest)
243 << Result.getLookupName() << isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000244 if (SS && NNS)
245 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
246 *CorrectedII = NewII;
247 return Ty;
248 }
249 }
250 }
251 // If typo correction failed or was not performed, fall through
Chris Lattner22bd9052009-02-16 22:07:16 +0000252 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000253 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000254 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000255 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000256
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000257 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000258 // Recover from type-hiding ambiguities by hiding the type. We'll
259 // do the lookup again when looking for an object, and we can
260 // diagnose the error then. If we don't do this, then the error
261 // about hiding the type will be immediately followed by an error
262 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000263 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
264 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000265 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000266 }
John McCall6e247262009-10-10 05:48:19 +0000267
Douglas Gregor31a19b62009-04-01 21:51:26 +0000268 // Look to see if we have a type anywhere in the list of results.
269 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
270 Res != ResEnd; ++Res) {
271 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000272 if (!IIDecl ||
273 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000274 IIDecl->getLocation().getRawEncoding())
275 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000276 }
277 }
278
279 if (!IIDecl) {
280 // None of the entities we found is a type, so there is no way
281 // to even assume that the result is a type. In this case, don't
282 // complain about the ambiguity. The parser will either try to
283 // perform this lookup again (e.g., as an object name), which
284 // will produce the ambiguity, or will complain that it expected
285 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000286 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000287 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000288 }
289
290 // We found a type within the ambiguous lookup; diagnose the
291 // ambiguity and then return that type. This might be the right
292 // answer, or it might not be, but it suppresses any attempt to
293 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000294 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000295
Chris Lattner22bd9052009-02-16 22:07:16 +0000296 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000297 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000298 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000299 }
300
Chris Lattner10ca3372009-10-25 17:16:46 +0000301 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000302
Chris Lattner10ca3372009-10-25 17:16:46 +0000303 QualType T;
304 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000305 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000306
Chris Lattner10ca3372009-10-25 17:16:46 +0000307 if (T.isNull())
308 T = Context.getTypeDeclType(TD);
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000309
310 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
311 // constructor or destructor name (in such a case, the scope specifier
312 // will be attached to the enclosing Expr or Decl node).
313 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor9e876872011-03-01 18:12:44 +0000314 if (WantNontrivialTypeSourceInfo) {
315 // Construct a type with type-source information.
316 TypeLocBuilder Builder;
317 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
318
319 T = getElaboratedType(ETK_None, *SS, T);
320 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +0000321 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor9e876872011-03-01 18:12:44 +0000322 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
323 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
324 } else {
325 T = getElaboratedType(ETK_None, *SS, T);
326 }
327 }
Chris Lattner10ca3372009-10-25 17:16:46 +0000328 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000329 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000330 if (!HasTrailingDot)
331 T = Context.getObjCInterfaceType(IDecl);
332 }
333
334 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000335 // If it's not plausibly a type, suppress diagnostics.
336 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000337 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000338 }
John McCallb3d87482010-08-24 05:47:05 +0000339 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000340}
341
Chris Lattner4c97d762009-04-12 21:49:30 +0000342/// isTagName() - This method is called *for error recovery purposes only*
343/// to determine if the specified name is a valid tag name ("struct foo"). If
344/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matos6666ed42012-08-31 18:45:21 +0000345/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
346/// cases in C where the user forgot to specify the tag.
Chris Lattner4c97d762009-04-12 21:49:30 +0000347DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
348 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000349 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
350 LookupName(R, S, false);
351 R.suppressDiagnostics();
352 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000353 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000354 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000355 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matos6666ed42012-08-31 18:45:21 +0000356 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000357 case TTK_Union: return DeclSpec::TST_union;
358 case TTK_Class: return DeclSpec::TST_class;
359 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000360 }
361 }
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner4c97d762009-04-12 21:49:30 +0000363 return DeclSpec::TST_unspecified;
364}
365
Francois Pichet6943e9b2011-04-13 02:38:49 +0000366/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
367/// if a CXXScopeSpec's type is equal to the type of one of the base classes
368/// then downgrade the missing typename error to a warning.
369/// This is needed for MSVC compatibility; Example:
370/// @code
371/// template<class T> class A {
372/// public:
373/// typedef int TYPE;
374/// };
375/// template<class T> class B : public A<T> {
376/// public:
377/// A<T>::TYPE a; // no typename required because A<T> is a base class.
378/// };
379/// @endcode
Francois Pichetf11dbe92011-10-11 01:50:09 +0000380bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000381 if (CurContext->isRecord()) {
Francois Pichet3441a522011-04-13 02:44:57 +0000382 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000383
384 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
385 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
386 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
387 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
388 return true;
Francois Pichetf11dbe92011-10-11 01:50:09 +0000389 return S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000390 }
Francois Pichetf11dbe92011-10-11 01:50:09 +0000391 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000392}
393
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000394bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000395 SourceLocation IILoc,
396 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000397 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000398 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000399 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000400 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000401
Douglas Gregor546be3c2009-12-30 17:04:44 +0000402 // There may have been a typo in the name of the type. Look up typo
403 // results, in case we have something that we can suggest.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000404 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000405 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000406 LookupOrdinaryName, S, SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000407 Validator)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000408 if (Corrected.isKeyword()) {
409 // We corrected to a keyword.
Richard Smith2d670972013-08-17 00:46:16 +0000410 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
411 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000412 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000413 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000414 if (!SS || !SS->isSet()) {
Richard Smith2d670972013-08-17 00:46:16 +0000415 diagnoseTypo(Corrected,
416 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000417 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +0000418 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
419 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000420 II->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000421 diagnoseTypo(Corrected,
422 PDiag(diag::err_unknown_nested_typename_suggest)
423 << II << DC << DroppedSpecifier << SS->getRange());
424 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000425 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000426 }
Douglas Gregor546be3c2009-12-30 17:04:44 +0000427
Richard Smith2d670972013-08-17 00:46:16 +0000428 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
429 IILoc, S, SS, false, false, ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000430 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000431 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor546be3c2009-12-30 17:04:44 +0000432 }
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000433 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000434 }
435
David Blaikie4e4d0842012-03-11 07:00:24 +0000436 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000437 // See if II is a class template that the user forgot to pass arguments to.
438 UnqualifiedId Name;
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000439 Name.setIdentifier(II, IILoc);
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000440 CXXScopeSpec EmptySS;
441 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000442 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000443 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000444 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000445 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov18062392013-08-27 13:15:56 +0000446 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000447 Diag(IILoc, diag::err_template_missing_args) << TplName;
448 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
449 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
450 << TplDecl->getTemplateParameters()->getSourceRange();
451 }
452 return true;
453 }
454 }
455
Douglas Gregora786fdb2009-10-13 23:27:22 +0000456 // FIXME: Should we move the logic that tries to recover from a missing tag
457 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
458
Douglas Gregor546be3c2009-12-30 17:04:44 +0000459 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000460 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregora786fdb2009-10-13 23:27:22 +0000461 else if (DeclContext *DC = computeDeclContext(*SS, false))
462 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000463 << II << DC << SS->getRange();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000464 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000465 unsigned DiagID = diag::err_typename_missing;
David Blaikie4e4d0842012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichetcf320c62011-04-22 08:25:24 +0000467 DiagID = diag::warn_typename_missing;
Francois Pichet6943e9b2011-04-13 02:38:49 +0000468
469 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000470 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000471 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000472 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000473 SuggestedType = ActOnTypenameType(S, SourceLocation(),
474 *SS, *II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000475 } else {
476 assert(SS && SS->isInvalid() &&
477 "Invalid scope specifier has already been diagnosed");
478 }
479
480 return true;
481}
Chris Lattner4c97d762009-04-12 21:49:30 +0000482
Douglas Gregor312eadb2011-04-24 05:37:28 +0000483/// \brief Determine whether the given result set contains either a type name
484/// or
485static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000486 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000487 NextToken.is(tok::less);
488
489 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
490 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
491 return true;
492
493 if (CheckTemplate && isa<TemplateDecl>(*I))
494 return true;
495 }
496
497 return false;
498}
499
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000500static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
501 Scope *S, CXXScopeSpec &SS,
502 IdentifierInfo *&Name,
503 SourceLocation NameLoc) {
Richard Smith69e48262012-09-06 01:37:56 +0000504 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
505 SemaRef.LookupParsedName(R, S, &SS);
506 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000507 const char *TagName = 0;
508 const char *FixItTagName = 0;
509 switch (Tag->getTagKind()) {
510 case TTK_Class:
511 TagName = "class";
512 FixItTagName = "class ";
513 break;
514
515 case TTK_Enum:
516 TagName = "enum";
517 FixItTagName = "enum ";
518 break;
519
520 case TTK_Struct:
521 TagName = "struct";
522 FixItTagName = "struct ";
523 break;
524
Joao Matos6666ed42012-08-31 18:45:21 +0000525 case TTK_Interface:
526 TagName = "__interface";
527 FixItTagName = "__interface ";
528 break;
529
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000530 case TTK_Union:
531 TagName = "union";
532 FixItTagName = "union ";
533 break;
534 }
535
536 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
537 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
538 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
539
Richard Smith69e48262012-09-06 01:37:56 +0000540 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
541 I != IEnd; ++I)
542 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
543 << Name << TagName;
544
545 // Replace lookup results with just the tag decl.
546 Result.clear(Sema::LookupTagName);
547 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000548 return true;
549 }
550
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000551 return false;
552}
553
Richard Smith05766812012-08-18 00:55:03 +0000554/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
555static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
556 QualType T, SourceLocation NameLoc) {
557 ASTContext &Context = S.Context;
558
559 TypeLocBuilder Builder;
560 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
561
562 T = S.getElaboratedType(ETK_None, SS, T);
563 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
564 ElabTL.setElaboratedKeywordLoc(SourceLocation());
565 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
566 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
567}
568
Douglas Gregor312eadb2011-04-24 05:37:28 +0000569Sema::NameClassification Sema::ClassifyName(Scope *S,
570 CXXScopeSpec &SS,
571 IdentifierInfo *&Name,
572 SourceLocation NameLoc,
Richard Smith05766812012-08-18 00:55:03 +0000573 const Token &NextToken,
574 bool IsAddressOfOperand,
575 CorrectionCandidateCallback *CCC) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000576 DeclarationNameInfo NameInfo(Name, NameLoc);
577 ObjCMethodDecl *CurMethod = getCurMethodDecl();
578
579 if (NextToken.is(tok::coloncolon)) {
580 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
581 QualType(), false, SS, 0, false);
582
583 }
584
585 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
586 LookupParsedName(Result, S, &SS, !CurMethod);
587
588 // Perform lookup for Objective-C instance variables (including automatically
589 // synthesized instance variables), if we're in an Objective-C method.
590 // FIXME: This lookup really, really needs to be folded in to the normal
591 // unqualified lookup mechanism.
592 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
593 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorec385cf2011-04-25 15:05:41 +0000594 if (E.get() || E.isInvalid())
Douglas Gregor312eadb2011-04-24 05:37:28 +0000595 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000596 }
597
598 bool SecondTry = false;
599 bool IsFilteredTemplateName = false;
600
601Corrected:
602 switch (Result.getResultKind()) {
603 case LookupResult::NotFound:
604 // If an unqualified-id is followed by a '(', then we have a function
605 // call.
606 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
607 // In C++, this is an ADL-only call.
608 // FIXME: Reference?
David Blaikie4e4d0842012-03-11 07:00:24 +0000609 if (getLangOpts().CPlusPlus)
Douglas Gregor312eadb2011-04-24 05:37:28 +0000610 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
611
612 // C90 6.3.2.2:
613 // If the expression that precedes the parenthesized argument list in a
614 // function call consists solely of an identifier, and if no
615 // declaration is visible for this identifier, the identifier is
616 // implicitly declared exactly as if, in the innermost block containing
617 // the function call, the declaration
618 //
619 // extern int identifier ();
620 //
621 // appeared.
622 //
623 // We also allow this in C99 as an extension.
624 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
625 Result.addDecl(D);
626 Result.resolveKind();
627 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
628 }
629 }
630
631 // In C, we first see whether there is a tag type by the same name, in
632 // which case it's likely that the user just forget to write "enum",
633 // "struct", or "union".
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000634 if (!getLangOpts().CPlusPlus && !SecondTry &&
635 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
636 break;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000637 }
638
639 // Perform typo correction to determine if there is another name that is
640 // close to this name.
Richard Smith05766812012-08-18 00:55:03 +0000641 if (!SecondTry && CCC) {
Douglas Gregor3a348c82011-07-14 04:54:23 +0000642 SecondTry = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000643 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikied662a792011-10-19 22:56:21 +0000644 Result.getLookupKind(), S,
Richard Smith05766812012-08-18 00:55:03 +0000645 &SS, *CCC)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000646 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
647 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smith2d670972013-08-17 00:46:16 +0000648
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000649 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor3b887352011-04-27 04:48:22 +0000650 NamedDecl *UnderlyingFirstDecl
651 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikie4e4d0842012-03-11 07:00:24 +0000652 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000653 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000654 UnqualifiedDiag = diag::err_no_template_suggest;
655 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor3b887352011-04-27 04:48:22 +0000656 } else if (UnderlyingFirstDecl &&
657 (isa<TypeDecl>(UnderlyingFirstDecl) ||
658 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
659 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie30262b72013-03-21 21:35:15 +0000660 UnqualifiedDiag = diag::err_unknown_typename_suggest;
661 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
662 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000663
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000664 if (SS.isEmpty()) {
Richard Smith2d670972013-08-17 00:46:16 +0000665 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000666 } else {// FIXME: is this even reachable? Test it.
Richard Smith2d670972013-08-17 00:46:16 +0000667 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
668 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000669 Name->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000670 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
671 << Name << computeDeclContext(SS, false)
672 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000673 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000674
675 // Update the name, so that the caller has the new name.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000676 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smith2d670972013-08-17 00:46:16 +0000677
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000678 // Typo correction corrected to a keyword.
679 if (Corrected.isKeyword())
Richard Smith2d670972013-08-17 00:46:16 +0000680 return Name;
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000681
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000682 // Also update the LookupResult...
683 // FIXME: This should probably go away at some point
684 Result.clear();
685 Result.setLookupName(Corrected.getCorrection());
Richard Smith2d670972013-08-17 00:46:16 +0000686 if (FirstDecl)
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000687 Result.addDecl(FirstDecl);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000688
689 // If we found an Objective-C instance variable, let
690 // LookupInObjCMethod build the appropriate expression to
691 // reference the ivar.
692 // FIXME: This is a gross hack.
693 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
694 Result.clear();
695 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000696 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000697 }
698
699 goto Corrected;
700 }
701 }
702
703 // We failed to correct; just fall through and let the parser deal with it.
704 Result.suppressDiagnostics();
705 return NameClassification::Unknown();
706
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000707 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000708 // We performed name lookup into the current instantiation, and there were
709 // dependent bases, so we treat this result the same way as any other
710 // dependent nested-name-specifier.
711
712 // C++ [temp.res]p2:
713 // A name used in a template declaration or definition and that is
714 // dependent on a template-parameter is assumed not to name a type
715 // unless the applicable name lookup finds a type name or the name is
716 // qualified by the keyword typename.
717 //
718 // FIXME: If the next token is '<', we might want to ask the parser to
719 // perform some heroics to see if we actually have a
720 // template-argument-list, which would indicate a missing 'template'
721 // keyword here.
Richard Smith05766812012-08-18 00:55:03 +0000722 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
723 NameInfo, IsAddressOfOperand,
724 /*TemplateArgs=*/0);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000725 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000726
727 case LookupResult::Found:
728 case LookupResult::FoundOverloaded:
729 case LookupResult::FoundUnresolvedValue:
730 break;
731
732 case LookupResult::Ambiguous:
David Blaikie4e4d0842012-03-11 07:00:24 +0000733 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000734 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000735 // C++ [temp.local]p3:
736 // A lookup that finds an injected-class-name (10.2) can result in an
737 // ambiguity in certain cases (for example, if it is found in more than
738 // one base class). If all of the injected-class-names that are found
739 // refer to specializations of the same class template, and if the name
740 // is followed by a template-argument-list, the reference refers to the
741 // class template itself and not a specialization thereof, and is not
742 // ambiguous.
743 //
744 // This filtering can make an ambiguous result into an unambiguous one,
745 // so try again after filtering out template names.
746 FilterAcceptableTemplateNames(Result);
747 if (!Result.isAmbiguous()) {
748 IsFilteredTemplateName = true;
749 break;
750 }
751 }
752
753 // Diagnose the ambiguity and return an error.
754 return NameClassification::Error();
755 }
756
David Blaikie4e4d0842012-03-11 07:00:24 +0000757 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000758 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
759 // C++ [temp.names]p3:
760 // After name lookup (3.4) finds that a name is a template-name or that
761 // an operator-function-id or a literal- operator-id refers to a set of
762 // overloaded functions any member of which is a function template if
763 // this is followed by a <, the < is always taken as the delimiter of a
764 // template-argument-list and never as the less-than operator.
765 if (!IsFilteredTemplateName)
766 FilterAcceptableTemplateNames(Result);
767
Douglas Gregor3b887352011-04-27 04:48:22 +0000768 if (!Result.empty()) {
769 bool IsFunctionTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000770 bool IsVarTemplate;
Douglas Gregor3b887352011-04-27 04:48:22 +0000771 TemplateName Template;
772 if (Result.end() - Result.begin() > 1) {
773 IsFunctionTemplate = true;
774 Template = Context.getOverloadedTemplateName(Result.begin(),
775 Result.end());
776 } else {
777 TemplateDecl *TD
778 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
779 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000780 IsVarTemplate = isa<VarTemplateDecl>(TD);
781
Douglas Gregor3b887352011-04-27 04:48:22 +0000782 if (SS.isSet() && !SS.isInvalid())
783 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000784 /*TemplateKeyword=*/false,
Douglas Gregor3b887352011-04-27 04:48:22 +0000785 TD);
786 else
787 Template = TemplateName(TD);
788 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000789
Douglas Gregor3b887352011-04-27 04:48:22 +0000790 if (IsFunctionTemplate) {
791 // Function templates always go through overload resolution, at which
792 // point we'll perform the various checks (e.g., accessibility) we need
793 // to based on which function we selected.
794 Result.suppressDiagnostics();
795
796 return NameClassification::FunctionTemplate(Template);
797 }
Larisse Voufoef4579c2013-08-06 01:03:05 +0000798
799 return IsVarTemplate ? NameClassification::VarTemplate(Template)
800 : NameClassification::TypeTemplate(Template);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000801 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000802 }
Richard Smith05766812012-08-18 00:55:03 +0000803
Douglas Gregor3b887352011-04-27 04:48:22 +0000804 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000805 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
806 DiagnoseUseOfDecl(Type, NameLoc);
807 QualType T = Context.getTypeDeclType(Type);
Richard Smith05766812012-08-18 00:55:03 +0000808 if (SS.isNotEmpty())
809 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000810 return ParsedType::make(T);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000811 }
Richard Smith05766812012-08-18 00:55:03 +0000812
Douglas Gregor312eadb2011-04-24 05:37:28 +0000813 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
814 if (!Class) {
815 // FIXME: It's unfortunate that we don't have a Type node for handling this.
816 if (ObjCCompatibleAliasDecl *Alias
817 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
818 Class = Alias->getClassInterface();
819 }
820
821 if (Class) {
822 DiagnoseUseOfDecl(Class, NameLoc);
823
824 if (NextToken.is(tok::period)) {
825 // Interface. <something> is parsed as a property reference expression.
826 // Just return "unknown" as a fall-through for now.
827 Result.suppressDiagnostics();
828 return NameClassification::Unknown();
829 }
830
831 QualType T = Context.getObjCInterfaceType(Class);
832 return ParsedType::make(T);
833 }
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000834
Richard Smith05766812012-08-18 00:55:03 +0000835 // We can have a type template here if we're classifying a template argument.
836 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
837 return NameClassification::TypeTemplate(
838 TemplateName(cast<TemplateDecl>(FirstDecl)));
839
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000840 // Check for a tag type hidden by a non-type decl in a few cases where it
841 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidis99e9fe02013-05-07 19:54:28 +0000842 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
843 if ((NextToken.is(tok::identifier) ||
844 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
845 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
847 DiagnoseUseOfDecl(Type, NameLoc);
848 QualType T = Context.getTypeDeclType(Type);
849 if (SS.isNotEmpty())
850 return buildNestedType(*this, SS, T, NameLoc);
851 return ParsedType::make(T);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000852 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000853
Richard Smith05766812012-08-18 00:55:03 +0000854 if (FirstDecl->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000855 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor3b887352011-04-27 04:48:22 +0000856
Douglas Gregor312eadb2011-04-24 05:37:28 +0000857 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
858 return BuildDeclarationNameExpr(SS, Result, ADL);
859}
860
John McCall88232aa2009-08-18 00:00:49 +0000861// Determines the context to return to after temporarily entering a
862// context. This depends in an unnecessarily complicated way on the
863// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000864DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000865
John McCall88232aa2009-08-18 00:00:49 +0000866 // Functions defined inline within classes aren't parsed until we've
867 // finished parsing the top-level class, so the top-level class is
868 // the context we'll need to return to.
869 if (isa<FunctionDecl>(DC)) {
870 DC = DC->getLexicalParent();
871
872 // A function not defined within a class will always return to its
873 // lexical context.
874 if (!isa<CXXRecordDecl>(DC))
875 return DC;
876
877 // A C++ inline method/friend is parsed *after* the topmost class
878 // it was declared in is fully parsed ("complete"); the topmost
879 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000880 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000881 DC = RD;
882
883 // Return the declaration context of the topmost class the inline method is
884 // declared in.
885 return DC;
886 }
887
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000888 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000889}
890
Douglas Gregor44b43212008-12-11 16:49:14 +0000891void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000892 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000893 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000894 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000895 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000896}
897
Chris Lattnerb048c982008-04-06 04:47:34 +0000898void Sema::PopDeclContext() {
899 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000900
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000901 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000902 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000903}
904
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000905/// EnterDeclaratorContext - Used when we must lookup names in the context
906/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000907///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000908void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000909 // C++0x [basic.lookup.unqual]p13:
910 // A name used in the definition of a static data member of class
911 // X (after the qualified-id of the static member) is looked up as
912 // if the name was used in a member function of X.
913 // C++0x [basic.lookup.unqual]p14:
914 // If a variable member of a namespace is defined outside of the
915 // scope of its namespace then any name used in the definition of
916 // the variable member (after the declarator-id) is looked up as
917 // if the definition of the variable member occurred in its
918 // namespace.
919 // Both of these imply that we should push a scope whose context
920 // is the semantic context of the declaration. We can't use
921 // PushDeclContext here because that context is not necessarily
922 // lexically contained in the current context. Fortunately,
923 // the containing scope should have the appropriate information.
924
925 assert(!S->getEntity() && "scope already has entity");
926
927#ifndef NDEBUG
928 Scope *Ancestor = S->getParent();
929 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
930 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
931#endif
932
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000933 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000934 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000935}
936
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000937void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000938 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000939
John McCall7a1dc562009-12-19 10:49:29 +0000940 // Switch back to the lexical context. The safety of this is
941 // enforced by an assert in EnterDeclaratorContext.
942 Scope *Ancestor = S->getParent();
943 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
944 CurContext = (DeclContext*) Ancestor->getEntity();
945
946 // We don't need to do anything with the scope, which is going to
947 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000948}
949
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000950
951void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
952 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
953 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
954 // We assume that the caller has already called
955 // ActOnReenterTemplateScope
956 FD = TFD->getTemplatedDecl();
957 }
958 if (!FD)
959 return;
960
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000961 // Same implementation as PushDeclContext, but enters the context
962 // from the lexical parent, rather than the top-level class.
963 assert(CurContext == FD->getLexicalParent() &&
964 "The next DeclContext should be lexically contained in the current one.");
965 CurContext = FD;
966 S->setEntity(CurContext);
967
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000968 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
969 ParmVarDecl *Param = FD->getParamDecl(P);
970 // If the parameter has an identifier, then add it to the scope
971 if (Param->getIdentifier()) {
972 S->AddDecl(Param);
973 IdResolver.AddDecl(Param);
974 }
975 }
976}
977
978
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000979void Sema::ActOnExitFunctionContext() {
980 // Same implementation as PopDeclContext, but returns to the lexical parent,
981 // rather than the top-level class.
982 assert(CurContext && "DeclContext imbalance!");
983 CurContext = CurContext->getLexicalParent();
984 assert(CurContext && "Popped translation unit!");
985}
986
987
Douglas Gregorf9201e02009-02-11 23:02:49 +0000988/// \brief Determine whether we allow overloading of the function
989/// PrevDecl with another declaration.
990///
991/// This routine determines whether overloading is possible, not
992/// whether some new function is actually an overload. It will return
993/// true in C++ (where we can always provide overloads) or, as an
994/// extension, in C when the previous function is already an
995/// overloaded function declaration or has the "overloadable"
996/// attribute.
John McCall68263142009-11-18 22:49:29 +0000997static bool AllowOverloadingOfFunction(LookupResult &Previous,
998 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000999 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001000 return true;
1001
John McCall68263142009-11-18 22:49:29 +00001002 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001003 return true;
1004
John McCall68263142009-11-18 22:49:29 +00001005 return (Previous.getResultKind() == LookupResult::Found
1006 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +00001007}
1008
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001009/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +00001010void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +00001011 // Move up the scope chain until we find the nearest enclosing
1012 // non-transparent context. The declaration will be introduced into this
1013 // scope.
Mike Stump1eb44332009-09-09 15:08:12 +00001014 while (S->getEntity() &&
Douglas Gregor074149e2009-01-05 19:45:36 +00001015 ((DeclContext *)S->getEntity())->isTransparentContext())
1016 S = S->getParent();
1017
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001018 // Add scoped declarations into their context, so that they can be
1019 // found later. Declarations without a context won't be inserted
1020 // into any context.
John McCallab88d972009-08-31 22:39:49 +00001021 if (AddToContext)
1022 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001023
Richard Smitha41c97a2013-09-20 01:15:31 +00001024 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1025 // are function-local declarations.
1026 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +00001027 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smitha41c97a2013-09-20 01:15:31 +00001028 D->getLexicalDeclContext()->getRedeclContext()) &&
1029 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruth8761d682010-02-21 07:08:09 +00001030 return;
1031
1032 // Template instantiations should also not be pushed into scope.
1033 if (isa<FunctionDecl>(D) &&
1034 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +00001035 return;
1036
John McCallf36e02d2009-10-09 21:13:30 +00001037 // If this replaces anything in the current scope,
1038 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1039 IEnd = IdResolver.end();
1040 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001041 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1042 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +00001043 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001044
John McCallf36e02d2009-10-09 21:13:30 +00001045 // Should only need to replace one decl.
1046 break;
Douglas Gregor516ff432009-04-24 02:57:34 +00001047 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001048 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001049
John McCalld226f652010-08-21 09:40:31 +00001050 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001051
1052 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1053 // Implicitly-generated labels may end up getting generated in an order that
1054 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1055 // the label at the appropriate place in the identifier chain.
1056 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +00001057 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +00001058 if (IDC == CurContext) {
1059 if (!S->isDeclScope(*I))
1060 continue;
1061 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001062 break;
1063 }
1064
Douglas Gregor250e7a72011-03-16 16:39:03 +00001065 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001066 } else {
1067 IdResolver.AddDecl(D);
1068 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001069}
1070
Douglas Gregoreee242f2011-10-27 09:33:13 +00001071void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1072 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1073 TUScope->AddDecl(D);
1074}
1075
Richard Smithdd9459f2013-08-13 18:18:50 +00001076bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001077 bool ExplicitInstantiationOrSpecialization) {
Nico Weber355a1662012-12-17 03:51:09 +00001078 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001079 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001080}
1081
John McCall5f1e0942010-08-24 08:50:51 +00001082Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1083 DeclContext *TargetDC = DC->getPrimaryContext();
1084 do {
1085 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1086 if (ScopeDC->getPrimaryContext() == TargetDC)
1087 return S;
1088 } while ((S = S->getParent()));
1089
1090 return 0;
1091}
1092
John McCall68263142009-11-18 22:49:29 +00001093static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1094 DeclContext*,
1095 ASTContext&);
1096
1097/// Filters out lookup results that don't fall within the given scope
1098/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001099void Sema::FilterLookupForScope(LookupResult &R,
1100 DeclContext *Ctx, Scope *S,
1101 bool ConsiderLinkage,
1102 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001103 LookupResult::Filter F = R.makeFilter();
1104 while (F.hasNext()) {
1105 NamedDecl *D = F.next();
1106
Richard Smith3e4c6c42011-05-05 21:57:07 +00001107 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001108 continue;
1109
1110 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001111 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001112 continue;
1113
1114 F.erase();
1115 }
1116
1117 F.done();
1118}
1119
1120static bool isUsingDecl(NamedDecl *D) {
1121 return isa<UsingShadowDecl>(D) ||
1122 isa<UnresolvedUsingTypenameDecl>(D) ||
1123 isa<UnresolvedUsingValueDecl>(D);
1124}
1125
1126/// Removes using shadow declarations from the lookup results.
1127static void RemoveUsingDecls(LookupResult &R) {
1128 LookupResult::Filter F = R.makeFilter();
1129 while (F.hasNext())
1130 if (isUsingDecl(F.next()))
1131 F.erase();
1132
1133 F.done();
1134}
1135
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001136/// \brief Check for this common pattern:
1137/// @code
1138/// class S {
1139/// S(const S&); // DO NOT IMPLEMENT
1140/// void operator=(const S&); // DO NOT IMPLEMENT
1141/// };
1142/// @endcode
1143static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1144 // FIXME: Should check for private access too but access is set after we get
1145 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001146 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001147 return false;
1148
1149 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1150 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001151 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1152 return Method->isCopyAssignmentOperator();
1153 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001154}
1155
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001156// We need this to handle
1157//
1158// typedef struct {
1159// void *foo() { return 0; }
1160// } A;
1161//
1162// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1163// for example. If 'A', foo will have external linkage. If we have '*A',
1164// foo will have no linkage. Since we can't know untill we get to the end
1165// of the typedef, this function finds out if D might have non external linkage.
1166// Callers should verify at the end of the TU if it D has external linkage or
1167// not.
1168bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1169 const DeclContext *DC = D->getDeclContext();
1170 while (!DC->isTranslationUnit()) {
1171 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1172 if (!RD->hasNameForLinkage())
1173 return true;
1174 }
1175 DC = DC->getParent();
1176 }
1177
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001178 return !D->isExternallyVisible();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001179}
1180
Eli Friedman39bd3712013-09-10 03:05:56 +00001181// FIXME: This needs to be refactored; some other isInMainFile users want
1182// these semantics.
1183static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1184 if (S.TUKind != TU_Complete)
1185 return false;
1186 return S.SourceMgr.isInMainFile(Loc);
1187}
1188
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001189bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1190 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001191
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001192 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1193 return false;
1194
1195 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001196 if (D->getDeclContext()->isDependentContext() ||
1197 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001198 return false;
1199
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001200 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001201 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1202 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001203
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001204 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1205 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1206 return false;
1207 } else {
Eli Friedman39bd3712013-09-10 03:05:56 +00001208 // 'static inline' functions are defined in headers; don't warn.
1209 if (FD->isInlineSpecified() &&
1210 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001211 return false;
1212 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001213
Sean Hunt10620eb2011-05-06 20:44:56 +00001214 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001215 Context.DeclMustBeEmitted(FD))
1216 return false;
John McCall82b96592010-10-27 01:41:35 +00001217 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman39bd3712013-09-10 03:05:56 +00001218 // Constants and utility variables are defined in headers with internal
1219 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1220 // like "inline".)
1221 if (!isMainFileLoc(*this, VD->getLocation()))
1222 return false;
1223
Eli Friedman39bd3712013-09-10 03:05:56 +00001224 if (Context.DeclMustBeEmitted(VD))
John McCall82b96592010-10-27 01:41:35 +00001225 return false;
1226
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001227 if (VD->isStaticDataMember() &&
1228 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1229 return false;
John McCall82b96592010-10-27 01:41:35 +00001230 } else {
1231 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001232 }
1233
John McCall82b96592010-10-27 01:41:35 +00001234 // Only warn for unused decls internal to the translation unit.
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001235 return mightHaveNonExternalLinkage(D);
John McCall82b96592010-10-27 01:41:35 +00001236}
1237
1238void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001239 if (!D)
1240 return;
1241
1242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1243 const FunctionDecl *First = FD->getFirstDeclaration();
1244 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1245 return; // First should already be in the vector.
1246 }
1247
1248 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1249 const VarDecl *First = VD->getFirstDeclaration();
1250 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1251 return; // First should already be in the vector.
1252 }
1253
David Blaikie7f7c42b2012-05-26 05:35:39 +00001254 if (ShouldWarnIfUnusedFileScopedDecl(D))
1255 UnusedFileScopedDecls.push_back(D);
1256}
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001257
Anders Carlsson99a000e2009-11-07 07:18:14 +00001258static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001259 if (D->isInvalidDecl())
1260 return false;
1261
Eli Friedmandd9d6452012-01-13 23:41:25 +00001262 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001263 return false;
John McCall86ff3082010-02-04 22:26:26 +00001264
Chris Lattner57ad3782011-02-17 20:34:02 +00001265 if (isa<LabelDecl>(D))
1266 return true;
1267
John McCall86ff3082010-02-04 22:26:26 +00001268 // White-list anything that isn't a local variable.
1269 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1270 !D->getDeclContext()->isFunctionOrMethod())
1271 return false;
1272
1273 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001274 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001275
1276 // White-list anything with an __attribute__((unused)) type.
1277 QualType Ty = VD->getType();
1278
1279 // Only look at the outermost level of typedef.
Douglas Gregor2c8e81e2012-09-14 05:10:40 +00001280 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallaec58602010-03-31 02:47:45 +00001281 if (TT->getDecl()->hasAttr<UnusedAttr>())
1282 return false;
1283 }
1284
Douglas Gregor5764f612010-05-08 23:05:03 +00001285 // If we failed to complete the type for some reason, or if the type is
1286 // dependent, don't diagnose the variable.
1287 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001288 return false;
1289
John McCallaec58602010-03-31 02:47:45 +00001290 if (const TagType *TT = Ty->getAs<TagType>()) {
1291 const TagDecl *Tag = TT->getDecl();
1292 if (Tag->hasAttr<UnusedAttr>())
1293 return false;
1294
1295 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001296 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001297 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001298
1299 if (const Expr *Init = VD->getInit()) {
David Blaikie39e17762012-10-24 21:29:06 +00001300 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1301 Init = Cleanups->getSubExpr();
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001302 const CXXConstructExpr *Construct =
1303 dyn_cast<CXXConstructExpr>(Init);
1304 if (Construct && !Construct->isElidable()) {
1305 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001306 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001307 return false;
1308 }
1309 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001310 }
1311 }
John McCallaec58602010-03-31 02:47:45 +00001312
1313 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001314 }
1315
John McCall86ff3082010-02-04 22:26:26 +00001316 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001317}
1318
Anna Zaksd5612a22011-07-28 20:52:06 +00001319static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1320 FixItHint &Hint) {
1321 if (isa<LabelDecl>(D)) {
1322 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001323 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001324 if (AfterColon.isInvalid())
1325 return;
1326 Hint = FixItHint::CreateRemoval(CharSourceRange::
1327 getCharRange(D->getLocStart(), AfterColon));
1328 }
1329 return;
1330}
1331
Chris Lattner337e5502011-02-18 01:27:55 +00001332/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1333/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001334void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001335 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001336 if (!ShouldDiagnoseUnusedDecl(D))
1337 return;
1338
Anna Zaksd5612a22011-07-28 20:52:06 +00001339 GenerateFixForUnusedDecl(D, Context, Hint);
1340
Chris Lattner57ad3782011-02-17 20:34:02 +00001341 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001342 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001343 DiagID = diag::warn_unused_exception_param;
1344 else if (isa<LabelDecl>(D))
1345 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001346 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001347 DiagID = diag::warn_unused_variable;
1348
Anna Zaksd5612a22011-07-28 20:52:06 +00001349 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001350}
1351
Chris Lattner337e5502011-02-18 01:27:55 +00001352static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1353 // Verify that we have no forward references left. If so, there was a goto
1354 // or address of a label taken, but no definition of it. Label fwd
1355 // definitions are indicated with a null substmt.
1356 if (L->getStmt() == 0)
1357 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1358}
1359
Steve Naroffb216c882007-10-09 22:01:59 +00001360void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001361 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001362 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001363 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1366 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001367 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001368 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001369
Douglas Gregor44b43212008-12-11 16:49:14 +00001370 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1371 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001372
Douglas Gregor44b43212008-12-11 16:49:14 +00001373 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001374
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001375 // Diagnose unused variables in this scope.
Matt Beaumont-Gay59d8ccb2013-03-28 21:46:45 +00001376 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001377 DiagnoseUnusedDecl(D);
1378
Chris Lattner337e5502011-02-18 01:27:55 +00001379 // If this was a forward reference to a label, verify it was defined.
1380 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1381 CheckPoppedLabel(LD, *this);
1382
Douglas Gregor44b43212008-12-11 16:49:14 +00001383 // Remove this name from our lexical scope.
1384 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 }
1386}
1387
James Molloy16f1f712012-02-29 10:24:19 +00001388void Sema::ActOnStartFunctionDeclarator() {
1389 ++InFunctionDeclarator;
1390}
1391
1392void Sema::ActOnEndFunctionDeclarator() {
1393 assert(InFunctionDeclarator);
1394 --InFunctionDeclarator;
1395}
1396
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001397/// \brief Look for an Objective-C class in the translation unit.
1398///
1399/// \param Id The name of the Objective-C class we're looking for. If
1400/// typo-correction fixes this name, the Id will be updated
1401/// to the fixed name.
1402///
1403/// \param IdLoc The location of the name in the translation unit.
1404///
James Dennett16ae9de2012-06-22 10:16:05 +00001405/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001406/// if there is no class with the given name.
1407///
1408/// \returns The declaration of the named Objective-C class, or NULL if the
1409/// class could not be found.
1410ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1411 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001412 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001413 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1414 // creation from this context.
1415 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1416
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001417 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001418 // Perform typo correction at the given location, but only if we
1419 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001420 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1421 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1422 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001423 Validator)) {
Richard Smith2d670972013-08-17 00:46:16 +00001424 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001425 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001426 Id = IDecl->getIdentifier();
1427 }
1428 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001429 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1430 // This routine must always return a class definition, if any.
1431 if (Def && Def->getDefinition())
1432 Def = Def->getDefinition();
1433 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001434}
1435
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001436/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1437/// from S, where a non-field would be declared. This routine copes
1438/// with the difference between C and C++ scoping rules in structs and
1439/// unions. For example, the following code is well-formed in C but
1440/// ill-formed in C++:
1441/// @code
1442/// struct S6 {
1443/// enum { BAR } e;
1444/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001445///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001446/// void test_S6() {
1447/// struct S6 a;
1448/// a.e = BAR;
1449/// }
1450/// @endcode
1451/// For the declaration of BAR, this routine will return a different
1452/// scope. The scope S will be the scope of the unnamed enumeration
1453/// within S6. In C++, this routine will return the scope associated
1454/// with S6, because the enumeration's scope is a transparent
1455/// context but structures can contain non-field names. In C, this
1456/// routine will return the translation unit scope, since the
1457/// enumeration's scope is a transparent context and structures cannot
1458/// contain non-field names.
1459Scope *Sema::getNonFieldDeclScope(Scope *S) {
1460 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001461 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001462 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001463 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001464 S = S->getParent();
1465 return S;
1466}
1467
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001468/// \brief Looks up the declaration of "struct objc_super" and
1469/// saves it for later use in building builtin declaration of
1470/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1471/// pre-existing declaration exists no action takes place.
1472static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1473 IdentifierInfo *II) {
1474 if (!II->isStr("objc_msgSendSuper"))
1475 return;
1476 ASTContext &Context = ThisSema.Context;
1477
1478 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1479 SourceLocation(), Sema::LookupTagName);
1480 ThisSema.LookupName(Result, S);
1481 if (Result.getResultKind() == LookupResult::Found)
1482 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1483 Context.setObjCSuperType(Context.getTagDeclType(TD));
1484}
1485
Douglas Gregor3e41d602009-02-13 23:20:09 +00001486/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1487/// file scope. lazily create a decl for it. ForRedeclaration is true
1488/// if we're creating this built-in in anticipation of redeclaring the
1489/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001490NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001491 Scope *S, bool ForRedeclaration,
1492 SourceLocation Loc) {
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001493 LookupPredefedObjCSuperType(*this, S, II);
1494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 Builtin::ID BID = (Builtin::ID)bid;
1496
Chris Lattner86df27b2009-06-14 00:45:47 +00001497 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001498 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001499 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001500 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001501 // Okay
1502 break;
1503
Mike Stumpf711c412009-07-28 23:57:15 +00001504 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001505 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001506 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001507 << Context.BuiltinInfo.GetName(BID);
1508 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001509
Mike Stumpf711c412009-07-28 23:57:15 +00001510 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001511 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001512 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001513 << Context.BuiltinInfo.GetName(BID);
1514 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001515
1516 case ASTContext::GE_Missing_ucontext:
1517 if (ForRedeclaration)
1518 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1519 << Context.BuiltinInfo.GetName(BID);
1520 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001521 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001522
1523 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1524 Diag(Loc, diag::ext_implicit_lib_function_decl)
1525 << Context.BuiltinInfo.GetName(BID)
1526 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001527 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001528 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001529 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001530 Diag(Loc, diag::note_please_include_header)
1531 << Context.BuiltinInfo.getHeaderName(BID)
1532 << Context.BuiltinInfo.GetName(BID);
1533 }
1534
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001535 FunctionDecl *New = FunctionDecl::Create(Context,
1536 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001537 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001538 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001539 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001540 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001541 New->setImplicit();
1542
Chris Lattner95e2c712008-05-05 22:18:14 +00001543 // Create Decl objects for each parameter, adding them to the
1544 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001545 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001546 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001547 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1548 ParmVarDecl *parm =
1549 ParmVarDecl::Create(Context, New, SourceLocation(),
1550 SourceLocation(), 0,
1551 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001552 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001553 parm->setScopeInfo(0, i);
1554 Params.push_back(parm);
1555 }
David Blaikie4278c652011-09-21 18:16:56 +00001556 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
1559 AddKnownFunctionAttributes(New);
1560
Chris Lattner7f925cc2008-04-11 07:00:53 +00001561 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001562 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1563 // relate Scopes to DeclContexts, and probably eliminate CurContext
1564 // entirely, but we're not there yet.
1565 DeclContext *SavedContext = CurContext;
1566 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001567 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001568 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 return New;
1570}
1571
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001572/// \brief Filter out any previous declarations that the given declaration
1573/// should not consider because they are not permitted to conflict, e.g.,
1574/// because they come from hidden sub-modules and do not refer to the same
1575/// entity.
1576static void filterNonConflictingPreviousDecls(ASTContext &context,
1577 NamedDecl *decl,
1578 LookupResult &previous){
1579 // This is only interesting when modules are enabled.
1580 if (!context.getLangOpts().Modules)
1581 return;
1582
1583 // Empty sets are uninteresting.
1584 if (previous.empty())
1585 return;
1586
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001587 LookupResult::Filter filter = previous.makeFilter();
1588 while (filter.hasNext()) {
1589 NamedDecl *old = filter.next();
1590
1591 // Non-hidden declarations are never ignored.
1592 if (!old->isHidden())
1593 continue;
1594
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001595 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001596 filter.erase();
1597 }
1598
1599 filter.done();
1600}
1601
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001602bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1603 QualType OldType;
1604 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1605 OldType = OldTypedef->getUnderlyingType();
1606 else
1607 OldType = Context.getTypeDeclType(Old);
1608 QualType NewType = New->getUnderlyingType();
1609
Douglas Gregorec3bd722012-01-11 22:33:48 +00001610 if (NewType->isVariablyModifiedType()) {
1611 // Must not redefine a typedef with a variably-modified type.
1612 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1613 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1614 << Kind << NewType;
1615 if (Old->getLocation().isValid())
1616 Diag(Old->getLocation(), diag::note_previous_definition);
1617 New->setInvalidDecl();
1618 return true;
1619 }
1620
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001621 if (OldType != NewType &&
1622 !OldType->isDependentType() &&
1623 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001624 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001625 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1626 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1627 << Kind << NewType << OldType;
1628 if (Old->getLocation().isValid())
1629 Diag(Old->getLocation(), diag::note_previous_definition);
1630 New->setInvalidDecl();
1631 return true;
1632 }
1633 return false;
1634}
1635
Richard Smith162e1c12011-04-15 14:24:37 +00001636/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001637/// same name and scope as a previous declaration 'Old'. Figure out
1638/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001639/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001640///
Richard Smith162e1c12011-04-15 14:24:37 +00001641void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001642 // If the new decl is known invalid already, don't bother doing any
1643 // merging checks.
1644 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Steve Naroff2b255c42008-09-09 14:32:20 +00001646 // Allow multiple definitions for ObjC built-in typedefs.
1647 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001648 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001649 const IdentifierInfo *TypeID = New->getIdentifier();
1650 switch (TypeID->getLength()) {
1651 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001652 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001653 {
1654 if (!TypeID->isStr("id"))
1655 break;
1656 QualType T = New->getUnderlyingType();
1657 if (!T->isPointerType())
1658 break;
1659 if (!T->isVoidPointerType()) {
1660 QualType PT = T->getAs<PointerType>()->getPointeeType();
1661 if (!PT->isStructureType())
1662 break;
1663 }
1664 Context.setObjCIdRedefinitionType(T);
1665 // Install the built-in type for 'id', ignoring the current definition.
1666 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1667 return;
1668 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001669 case 5:
1670 if (!TypeID->isStr("Class"))
1671 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001672 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001673 // Install the built-in type for 'Class', ignoring the current definition.
1674 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001675 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001676 case 3:
1677 if (!TypeID->isStr("SEL"))
1678 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001679 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001680 // Install the built-in type for 'SEL', ignoring the current definition.
1681 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001682 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001683 }
1684 // Fall through - the typedef name was not a builtin type.
1685 }
John McCall68263142009-11-18 22:49:29 +00001686
Douglas Gregor66973122009-01-28 17:15:10 +00001687 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001688 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1689 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001690 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001691 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001692
1693 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001694 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001695 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001696
Chris Lattnereaaebc72009-04-25 08:06:05 +00001697 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 }
Douglas Gregor66973122009-01-28 17:15:10 +00001699
John McCall68263142009-11-18 22:49:29 +00001700 // If the old declaration is invalid, just give up here.
1701 if (Old->isInvalidDecl())
1702 return New->setInvalidDecl();
1703
Chris Lattner99cb9972008-07-25 18:44:27 +00001704 // If the typedef types are not identical, reject them in all languages and
1705 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001706 if (isIncompatibleTypedef(Old, New))
1707 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001708
John McCall5126fd02009-12-30 00:31:22 +00001709 // The types match. Link up the redeclaration chain if the old
1710 // declaration was a typedef.
Richard Smith162e1c12011-04-15 14:24:37 +00001711 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1712 New->setPreviousDeclaration(Typedef);
John McCall5126fd02009-12-30 00:31:22 +00001713
Eli Friedman9ec40992013-07-16 02:07:49 +00001714 mergeDeclAttributes(New, Old);
1715
David Blaikie4e4d0842012-03-11 07:00:24 +00001716 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001717 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001718
David Blaikie4e4d0842012-03-11 07:00:24 +00001719 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001720 // C++ [dcl.typedef]p2:
1721 // In a given non-class scope, a typedef specifier can be used to
1722 // redefine the name of any type declared in that scope to refer
1723 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001724 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001725 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001726
1727 // C++0x [dcl.typedef]p4:
1728 // In a given class scope, a typedef specifier can be used to redefine
1729 // any class-name declared in that scope that is not also a typedef-name
1730 // to refer to the type to which it already refers.
1731 //
1732 // This wording came in via DR424, which was a correction to the
1733 // wording in DR56, which accidentally banned code like:
1734 //
1735 // struct S {
1736 // typedef struct A { } A;
1737 // };
1738 //
1739 // in the C++03 standard. We implement the C++0x semantics, which
1740 // allow the above but disallow
1741 //
1742 // struct S {
1743 // typedef int I;
1744 // typedef int I;
1745 // };
1746 //
1747 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001748 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001749 return;
1750
Chris Lattner32b06752009-04-17 22:04:20 +00001751 Diag(New->getLocation(), diag::err_redefinition)
1752 << New->getDeclName();
1753 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001754 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001755 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001756
Douglas Gregorc0004df2012-01-11 04:25:01 +00001757 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001758 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001759 return;
1760
Chris Lattner32b06752009-04-17 22:04:20 +00001761 // If we have a redefinition of a typedef in C, emit a warning. This warning
1762 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001763 // -Wtypedef-redefinition. If either the original or the redefinition is
1764 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001765 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001766 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1767 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001768 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Chris Lattner32b06752009-04-17 22:04:20 +00001770 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1771 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001772 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001773 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001774}
1775
Chris Lattner6b6b5372008-06-26 18:38:35 +00001776/// DeclhasAttr - returns true if decl Declaration already has the target
1777/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001778static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001779DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001780 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1781 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1782 // responsible for making sure they are consistent.
1783 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1784 if (AA)
1785 return false;
1786
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001787 // The following thread safety attributes can also be duplicated.
1788 switch (A->getKind()) {
1789 case attr::ExclusiveLocksRequired:
1790 case attr::SharedLocksRequired:
1791 case attr::LocksExcluded:
1792 case attr::ExclusiveLockFunction:
1793 case attr::SharedLockFunction:
1794 case attr::UnlockFunction:
1795 case attr::ExclusiveTrylockFunction:
1796 case attr::SharedTrylockFunction:
1797 case attr::GuardedBy:
1798 case attr::PtGuardedBy:
1799 case attr::AcquiredBefore:
1800 case attr::AcquiredAfter:
1801 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001802 default:
1803 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001804 }
1805
Sean Huntcf807c42010-08-18 23:23:40 +00001806 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001807 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001808 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1809 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001810 if (Ann) {
1811 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1812 return true;
1813 continue;
1814 }
Sean Huntcf807c42010-08-18 23:23:40 +00001815 // FIXME: Don't hardcode this check
1816 if (OA && isa<OwnershipAttr>(*i))
1817 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001818 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001819 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001820
1821 return false;
1822}
1823
Richard Smith671b3212013-02-22 04:55:39 +00001824static bool isAttributeTargetADefinition(Decl *D) {
1825 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1826 return VD->isThisDeclarationADefinition();
1827 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1828 return TD->isCompleteDefinition() || TD->isBeingDefined();
1829 return true;
1830}
1831
1832/// Merge alignment attributes from \p Old to \p New, taking into account the
1833/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1834///
1835/// \return \c true if any attributes were added to \p New.
1836static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1837 // Look for alignas attributes on Old, and pick out whichever attribute
1838 // specifies the strictest alignment requirement.
1839 AlignedAttr *OldAlignasAttr = 0;
1840 AlignedAttr *OldStrictestAlignAttr = 0;
1841 unsigned OldAlign = 0;
1842 for (specific_attr_iterator<AlignedAttr>
1843 I = Old->specific_attr_begin<AlignedAttr>(),
1844 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1845 // FIXME: We have no way of representing inherited dependent alignments
1846 // in a case like:
1847 // template<int A, int B> struct alignas(A) X;
1848 // template<int A, int B> struct alignas(B) X {};
1849 // For now, we just ignore any alignas attributes which are not on the
1850 // definition in such a case.
1851 if (I->isAlignmentDependent())
1852 return false;
1853
1854 if (I->isAlignas())
1855 OldAlignasAttr = *I;
1856
1857 unsigned Align = I->getAlignment(S.Context);
1858 if (Align > OldAlign) {
1859 OldAlign = Align;
1860 OldStrictestAlignAttr = *I;
1861 }
1862 }
1863
1864 // Look for alignas attributes on New.
1865 AlignedAttr *NewAlignasAttr = 0;
1866 unsigned NewAlign = 0;
1867 for (specific_attr_iterator<AlignedAttr>
1868 I = New->specific_attr_begin<AlignedAttr>(),
1869 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1870 if (I->isAlignmentDependent())
1871 return false;
1872
1873 if (I->isAlignas())
1874 NewAlignasAttr = *I;
1875
1876 unsigned Align = I->getAlignment(S.Context);
1877 if (Align > NewAlign)
1878 NewAlign = Align;
1879 }
1880
1881 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1882 // Both declarations have 'alignas' attributes. We require them to match.
1883 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1884 // fall short. (If two declarations both have alignas, they must both match
1885 // every definition, and so must match each other if there is a definition.)
1886
1887 // If either declaration only contains 'alignas(0)' specifiers, then it
1888 // specifies the natural alignment for the type.
1889 if (OldAlign == 0 || NewAlign == 0) {
1890 QualType Ty;
1891 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1892 Ty = VD->getType();
1893 else
1894 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1895
1896 if (OldAlign == 0)
1897 OldAlign = S.Context.getTypeAlign(Ty);
1898 if (NewAlign == 0)
1899 NewAlign = S.Context.getTypeAlign(Ty);
1900 }
1901
1902 if (OldAlign != NewAlign) {
1903 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1904 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1905 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1906 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1907 }
1908 }
1909
1910 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1911 // C++11 [dcl.align]p6:
1912 // if any declaration of an entity has an alignment-specifier,
1913 // every defining declaration of that entity shall specify an
1914 // equivalent alignment.
1915 // C11 6.7.5/7:
1916 // If the definition of an object does not have an alignment
1917 // specifier, any other declaration of that object shall also
1918 // have no alignment specifier.
1919 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1920 << OldAlignasAttr->isC11();
1921 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1922 << OldAlignasAttr->isC11();
1923 }
1924
1925 bool AnyAdded = false;
1926
1927 // Ensure we have an attribute representing the strictest alignment.
1928 if (OldAlign > NewAlign) {
1929 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1930 Clone->setInherited(true);
1931 New->addAttr(Clone);
1932 AnyAdded = true;
1933 }
1934
1935 // Ensure we have an alignas attribute if the old declaration had one.
1936 if (OldAlignasAttr && !NewAlignasAttr &&
1937 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1938 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1939 Clone->setInherited(true);
1940 New->addAttr(Clone);
1941 AnyAdded = true;
1942 }
1943
1944 return AnyAdded;
1945}
1946
1947static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1948 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001949 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001950 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001951 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001952 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1953 AA->getIntroduced(), AA->getDeprecated(),
1954 AA->getObsoleted(), AA->getUnavailable(),
1955 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001956 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001957 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1958 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1959 AttrSpellingListIndex);
1960 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1961 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1962 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001963 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001964 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1965 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001966 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001967 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1968 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001969 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001970 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1971 FA->getFormatIdx(), FA->getFirstArg(),
1972 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001973 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001974 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1975 AttrSpellingListIndex);
1976 else if (isa<AlignedAttr>(Attr))
1977 // AlignedAttrs are handled separately, because we need to handle all
1978 // such attributes on a declaration at the same time.
1979 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00001980 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001981 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00001982
Rafael Espindola599f1b72012-05-13 03:25:18 +00001983 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00001984 NewAttr->setInherited(true);
1985 D->addAttr(NewAttr);
1986 return true;
1987 }
1988
1989 return false;
1990}
1991
Rafael Espindola4b044c62012-07-15 01:05:36 +00001992static const Decl *getDefinition(const Decl *D) {
1993 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00001994 return TD->getDefinition();
Rafael Espindola4b044c62012-07-15 01:05:36 +00001995 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00001996 return VD->getDefinition();
Rafael Espindola4b044c62012-07-15 01:05:36 +00001997 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00001998 const FunctionDecl* Def;
1999 if (FD->hasBody(Def))
2000 return Def;
2001 }
2002 return NULL;
2003}
2004
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002005static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2006 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2007 I != E; ++I) {
2008 Attr *Attribute = *I;
2009 if (Attribute->getKind() == Kind)
2010 return true;
2011 }
2012 return false;
2013}
2014
2015/// checkNewAttributesAfterDef - If we already have a definition, check that
2016/// there are no new attributes in this declaration.
2017static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2018 if (!New->hasAttrs())
2019 return;
2020
2021 const Decl *Def = getDefinition(Old);
2022 if (!Def || Def == New)
2023 return;
2024
2025 AttrVec &NewAttributes = New->getAttrs();
2026 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2027 const Attr *NewAttribute = NewAttributes[I];
2028 if (hasAttribute(Def, NewAttribute->getKind())) {
2029 ++I;
2030 continue; // regular attr merging will take care of validating this.
2031 }
Richard Smith671b3212013-02-22 04:55:39 +00002032
Richard Smith7586a6e2013-01-30 05:45:05 +00002033 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002034 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002035 ++I;
2036 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002037 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2038 if (AA->isAlignas()) {
2039 // C++11 [dcl.align]p6:
2040 // if any declaration of an entity has an alignment-specifier,
2041 // every defining declaration of that entity shall specify an
2042 // equivalent alignment.
2043 // C11 6.7.5/7:
2044 // If the definition of an object does not have an alignment
2045 // specifier, any other declaration of that object shall also
2046 // have no alignment specifier.
2047 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2048 << AA->isC11();
2049 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2050 << AA->isC11();
2051 NewAttributes.erase(NewAttributes.begin() + I);
2052 --E;
2053 continue;
2054 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002055 }
Richard Smith671b3212013-02-22 04:55:39 +00002056
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002057 S.Diag(NewAttribute->getLocation(),
2058 diag::warn_attribute_precede_definition);
2059 S.Diag(Def->getLocation(), diag::note_previous_definition);
2060 NewAttributes.erase(NewAttributes.begin() + I);
2061 --E;
2062 }
2063}
2064
John McCalleca5d222011-03-02 04:00:57 +00002065/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002066void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002067 AvailabilityMergeKind AMK) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002068 if (!Old->hasAttrs() && !New->hasAttrs())
2069 return;
2070
Rafael Espindola3f664062012-05-18 01:47:00 +00002071 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002072 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002073
Douglas Gregor27c6da22012-01-01 20:30:41 +00002074 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002075 return;
John McCalleca5d222011-03-02 04:00:57 +00002076
Douglas Gregor27c6da22012-01-01 20:30:41 +00002077 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002078
Sean Huntcf807c42010-08-18 23:23:40 +00002079 // Ensure that any moving of objects within the allocated map is done before
2080 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002081 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002082
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002083 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002084 i = Old->specific_attr_begin<InheritableAttr>(),
2085 e = Old->specific_attr_end<InheritableAttr>();
2086 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002087 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002088 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002089 if (isa<DeprecatedAttr>(*i) ||
2090 isa<UnavailableAttr>(*i) ||
2091 isa<AvailabilityAttr>(*i)) {
2092 switch (AMK) {
2093 case AMK_None:
2094 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002095
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002096 case AMK_Redeclaration:
2097 break;
2098
2099 case AMK_Override:
2100 Override = true;
2101 break;
2102 }
2103 }
2104
Richard Smith671b3212013-02-22 04:55:39 +00002105 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002106 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002107 }
John McCalleca5d222011-03-02 04:00:57 +00002108
Richard Smith671b3212013-02-22 04:55:39 +00002109 if (mergeAlignedAttrs(*this, New, Old))
2110 foundAny = true;
2111
Douglas Gregor27c6da22012-01-01 20:30:41 +00002112 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002113}
2114
2115/// mergeParamDeclAttributes - Copy attributes from the old parameter
2116/// to the new one.
2117static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2118 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002119 Sema &S) {
2120 // C++11 [dcl.attr.depend]p2:
2121 // The first declaration of a function shall specify the
2122 // carries_dependency attribute for its declarator-id if any declaration
2123 // of the function specifies the carries_dependency attribute.
2124 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2125 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2126 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2127 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2128 // Find the first declaration of the parameter.
2129 // FIXME: Should we build redeclaration chains for function parameters?
2130 const FunctionDecl *FirstFD =
2131 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration();
2132 const ParmVarDecl *FirstVD =
2133 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2134 S.Diag(FirstVD->getLocation(),
2135 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2136 }
2137
John McCalleca5d222011-03-02 04:00:57 +00002138 if (!oldDecl->hasAttrs())
2139 return;
2140
2141 bool foundAny = newDecl->hasAttrs();
2142
2143 // Ensure that any moving of objects within the allocated map is
2144 // done before we process them.
2145 if (!foundAny) newDecl->setAttrs(AttrVec());
2146
2147 for (specific_attr_iterator<InheritableParamAttr>
2148 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2149 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2150 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002151 InheritableAttr *newAttr =
2152 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002153 newAttr->setInherited(true);
2154 newDecl->addAttr(newAttr);
2155 foundAny = true;
2156 }
2157 }
2158
2159 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002160}
2161
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002162namespace {
2163
Douglas Gregorc8376562009-03-06 22:43:54 +00002164/// Used in MergeFunctionDecl to keep track of function parameters in
2165/// C.
2166struct GNUCompatibleParamWarning {
2167 ParmVarDecl *OldParm;
2168 ParmVarDecl *NewParm;
2169 QualType PromotedType;
2170};
2171
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002172}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002173
2174/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002175Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002176 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002177 if (Ctor->isDefaultConstructor())
2178 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002179
2180 if (Ctor->isCopyConstructor())
2181 return Sema::CXXCopyConstructor;
2182
2183 if (Ctor->isMoveConstructor())
2184 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002185 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002186 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002187 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002188 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002189 } else if (MD->isMoveAssignmentOperator()) {
2190 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002191 }
Sean Huntf961ea52011-05-10 19:08:14 +00002192
Sean Huntf961ea52011-05-10 19:08:14 +00002193 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002194}
2195
Sebastian Redl515ddd82010-06-09 21:17:41 +00002196/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002197/// only extern inline functions can be redefined, and even then only in
2198/// GNU89 mode.
2199static bool canRedefineFunction(const FunctionDecl *FD,
2200 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002201 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2202 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002203 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002204 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002205}
2206
Reid Kleckneref072032013-08-27 23:08:25 +00002207const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2208 const AttributedType *AT = T->getAs<AttributedType>();
2209 while (AT && !AT->isCallingConv())
2210 AT = AT->getModifiedType()->getAs<AttributedType>();
2211 return AT;
John McCallfb609142012-08-25 02:00:03 +00002212}
2213
Benjamin Kramera574c892013-02-15 12:30:38 +00002214template <typename T>
2215static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002216 const DeclContext *DC = Old->getDeclContext();
2217 if (DC->isRecord())
2218 return false;
2219
2220 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002221 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002222 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002223 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002224 return true;
2225 return false;
2226}
2227
Chris Lattner04421082008-04-08 04:40:51 +00002228/// MergeFunctionDecl - We just parsed a function 'New' from
2229/// declarator D which has the same name and scope as a previous
2230/// declaration 'Old'. Figure out how to resolve this situation,
2231/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002232///
2233/// In C++, New and Old must be declarations that are not
2234/// overloaded. Use IsOverload to determine whether New and Old are
2235/// overloaded, and to select the Old declaration that New should be
2236/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002237///
2238/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002239bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2240 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002242 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002243 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002244 = dyn_cast<FunctionTemplateDecl>(OldD))
2245 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002246 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002247 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002249 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002250 if (New->getFriendObjectKind()) {
2251 Diag(New->getLocation(), diag::err_using_decl_friend);
2252 Diag(Shadow->getTargetDecl()->getLocation(),
2253 diag::note_using_decl_target);
2254 Diag(Shadow->getUsingDecl()->getLocation(),
2255 diag::note_using_decl) << 0;
2256 return true;
2257 }
2258
John McCall41ce66f2009-12-10 19:51:03 +00002259 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2260 Diag(Shadow->getTargetDecl()->getLocation(),
2261 diag::note_using_decl_target);
2262 Diag(Shadow->getUsingDecl()->getLocation(),
2263 diag::note_using_decl) << 0;
2264 return true;
2265 }
2266
Chris Lattner5dc266a2008-11-20 06:13:02 +00002267 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002268 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002269 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002270 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002272
David Majnemerbcd06502013-07-07 23:49:50 +00002273 // If the old declaration is invalid, just give up here.
2274 if (Old->isInvalidDecl())
2275 return true;
2276
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002277 // Determine whether the previous declaration was a definition,
2278 // implicit declaration, or a declaration.
2279 diag::kind PrevDiag;
2280 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002281 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002282 else if (Old->isImplicit())
2283 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002284 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002285 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002287 // Don't complain about this if we're in GNU89 mode and the old function
2288 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002289 // Don't complain about specializations. They are not supposed to have
2290 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002291 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002292 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002293 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002294 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002295 !canRedefineFunction(Old, getLangOpts())) {
2296 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002297 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2298 Diag(Old->getLocation(), PrevDiag);
2299 } else {
2300 Diag(New->getLocation(), diag::err_static_non_static) << New;
2301 Diag(Old->getLocation(), PrevDiag);
2302 return true;
2303 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002304 }
2305
Reid Kleckneref072032013-08-27 23:08:25 +00002306
2307 // If a function is first declared with a calling convention, but is later
2308 // declared or defined without one, all following decls assume the calling
2309 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002310 //
John McCallfb609142012-08-25 02:00:03 +00002311 // It's OK if a function is first declared without a calling convention,
2312 // but is later declared or defined with the default calling convention.
2313 //
Reid Kleckneref072032013-08-27 23:08:25 +00002314 // To test if either decl has an explicit calling convention, we look for
2315 // AttributedType sugar nodes on the type as written. If they are missing or
2316 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002317 //
2318 // Note also that we DO NOT return at this point, because we still have
2319 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002320 QualType OldQType = Context.getCanonicalType(Old->getType());
2321 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002322 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002323 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002324 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2325 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2326 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002327
Reid Kleckneref072032013-08-27 23:08:25 +00002328 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2329 FunctionDecl *First = Old->getFirstDeclaration();
2330 const FunctionType *FT =
2331 First->getType().getCanonicalType()->castAs<FunctionType>();
2332 FunctionType::ExtInfo FI = FT->getExtInfo();
2333 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2334 if (!NewCCExplicit) {
2335 // Inherit the CC from the previous declaration if it was specified
2336 // there but not here.
2337 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2338 RequiresAdjustment = true;
2339 } else {
2340 // Calling conventions aren't compatible, so complain.
2341 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2342 Diag(New->getLocation(), diag::err_cconv_change)
2343 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2344 << !FirstCCExplicit
2345 << (!FirstCCExplicit ? "" :
2346 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002347
Reid Kleckneref072032013-08-27 23:08:25 +00002348 // Put the note on the first decl, since it is the one that matters.
2349 Diag(First->getLocation(), diag::note_previous_declaration);
2350 return true;
2351 }
John McCallf82b4e82010-02-04 05:44:44 +00002352 }
2353
John McCall04a67a62010-02-05 21:31:56 +00002354 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002355 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2356 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2357 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002358 }
2359
Douglas Gregord2c64902010-06-18 21:30:25 +00002360 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002361 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2362 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2363 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002364 Diag(New->getLocation(), diag::err_regparm_mismatch)
2365 << NewType->getRegParmType()
2366 << OldType->getRegParmType();
2367 Diag(Old->getLocation(), diag::note_previous_declaration);
2368 return true;
2369 }
John McCalle6a365d2010-12-19 02:44:49 +00002370
2371 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2372 RequiresAdjustment = true;
2373 }
2374
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002375 // Merge ns_returns_retained attribute.
2376 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2377 if (NewTypeInfo.getProducesResult()) {
2378 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2379 Diag(Old->getLocation(), diag::note_previous_declaration);
2380 return true;
2381 }
2382
2383 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2384 RequiresAdjustment = true;
2385 }
2386
John McCalle6a365d2010-12-19 02:44:49 +00002387 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002388 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2389 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2390 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002391 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002392 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002393 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002394
2395 // If this redeclaration makes the function inline, we may need to add it to
2396 // UndefinedButUsed.
2397 if (!Old->isInlined() && New->isInlined() &&
2398 !New->hasAttr<GNUInlineAttr>() &&
2399 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2400 Old->isUsed(false) &&
2401 !Old->isDefined() && !New->isThisDeclarationADefinition())
2402 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2403 SourceLocation()));
2404
2405 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2406 // about it.
2407 if (New->hasAttr<GNUInlineAttr>() &&
2408 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2409 UndefinedButUsed.erase(Old->getCanonicalDecl());
2410 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002411
David Blaikie4e4d0842012-03-11 07:00:24 +00002412 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002413 // (C++98 13.1p2):
2414 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002415 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002416 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002417
2418 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002419 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002420 // Redeclarations or specializations of a function or function template
2421 // with a declared return type that uses a placeholder type shall also
2422 // use that placeholder, not a deduced type.
2423 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2424 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2425 : OldType)->getResultType();
2426 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2427 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2428 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002429 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002430 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2431 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2432 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002433 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2434 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002435 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2436 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002437 if (New->isCXXClassMember() && New->isOutOfLine())
2438 Diag(New->getLocation(),
2439 diag::err_member_def_does_not_match_ret_type) << New;
2440 else
2441 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002442 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2443 return true;
2444 }
2445 else
2446 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002447 }
2448
Richard Smith60e141e2013-05-04 07:00:32 +00002449 QualType OldReturnType = OldType->getResultType();
2450 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2451 if (OldReturnType != NewReturnType) {
2452 // If this function has a deduced return type and has already been
2453 // defined, copy the deduced value from the old declaration.
2454 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2455 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002456 New->setType(
2457 SubstAutoType(New->getType(),
2458 OldAT->isDependentType() ? Context.DependentTy
2459 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002460 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002461 SubstAutoType(NewQType,
2462 OldAT->isDependentType() ? Context.DependentTy
2463 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002464 }
2465 }
2466
2467 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2468 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002469 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002470 // Preserve triviality.
2471 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002472
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002473 // MSVC allows explicit template specialization at class scope:
2474 // 2 CXMethodDecls referring to the same function will be injected.
2475 // We don't want a redeclartion error.
2476 bool IsClassScopeExplicitSpecialization =
2477 OldMethod->isFunctionTemplateSpecialization() &&
2478 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002479 bool isFriend = NewMethod->getFriendObjectKind();
2480
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002481 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2482 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002483 // -- Member function declarations with the same name and the
2484 // same parameter types cannot be overloaded if any of them
2485 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002486 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002487 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2488 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2489 return true;
2490 }
Richard Smith838925d2012-07-13 04:12:04 +00002491
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002492 // C++ [class.mem]p1:
2493 // [...] A member shall not be declared twice in the
2494 // member-specification, except that a nested class or member
2495 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002496 if (ActiveTemplateInstantiations.empty()) {
2497 unsigned NewDiag;
2498 if (isa<CXXConstructorDecl>(OldMethod))
2499 NewDiag = diag::err_constructor_redeclared;
2500 else if (isa<CXXDestructorDecl>(NewMethod))
2501 NewDiag = diag::err_destructor_redeclared;
2502 else if (isa<CXXConversionDecl>(NewMethod))
2503 NewDiag = diag::err_conv_function_redeclared;
2504 else
2505 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002506
Richard Smith838925d2012-07-13 04:12:04 +00002507 Diag(New->getLocation(), NewDiag);
2508 } else {
2509 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2510 << New << New->getType();
2511 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002512 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002513
2514 // Complain if this is an explicit declaration of a special
2515 // member that was initially declared implicitly.
2516 //
2517 // As an exception, it's okay to befriend such methods in order
2518 // to permit the implicit constructor/destructor/operator calls.
2519 } else if (OldMethod->isImplicit()) {
2520 if (isFriend) {
2521 NewMethod->setImplicit();
2522 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002523 Diag(NewMethod->getLocation(),
2524 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002525 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002526 return true;
2527 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002528 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002529 Diag(NewMethod->getLocation(),
2530 diag::err_definition_of_explicitly_defaulted_member)
2531 << getSpecialMember(OldMethod);
2532 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002533 }
2534 }
2535
Richard Smithcd8ab512013-01-17 01:30:42 +00002536 // C++11 [dcl.attr.noreturn]p1:
2537 // The first declaration of a function shall specify the noreturn
2538 // attribute if any declaration of that function specifies the noreturn
2539 // attribute.
2540 if (New->hasAttr<CXX11NoReturnAttr>() &&
2541 !Old->hasAttr<CXX11NoReturnAttr>()) {
2542 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2543 diag::err_noreturn_missing_on_first_decl);
2544 Diag(Old->getFirstDeclaration()->getLocation(),
2545 diag::note_noreturn_missing_first_decl);
2546 }
2547
Richard Smith3a2b7a12013-01-28 22:42:45 +00002548 // C++11 [dcl.attr.depend]p2:
2549 // The first declaration of a function shall specify the
2550 // carries_dependency attribute for its declarator-id if any declaration
2551 // of the function specifies the carries_dependency attribute.
2552 if (New->hasAttr<CarriesDependencyAttr>() &&
2553 !Old->hasAttr<CarriesDependencyAttr>()) {
2554 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2555 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2556 Diag(Old->getFirstDeclaration()->getLocation(),
2557 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2558 }
2559
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002560 // (C++98 8.3.5p3):
2561 // All declarations for a function shall agree exactly in both the
2562 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002563 // We also want to respect all the extended bits except noreturn.
2564
2565 // noreturn should now match unless the old type info didn't have it.
2566 QualType OldQTypeForComparison = OldQType;
2567 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2568 assert(OldQType == QualType(OldType, 0));
2569 const FunctionType *OldTypeForComparison
2570 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2571 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2572 assert(OldQTypeForComparison.isCanonical());
2573 }
2574
Rafael Espindola950fee22013-02-14 01:18:37 +00002575 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002576 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2577 Diag(Old->getLocation(), PrevDiag);
2578 return true;
2579 }
2580
John McCalle6a365d2010-12-19 02:44:49 +00002581 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002582 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002583
Richard Smitha41c97a2013-09-20 01:15:31 +00002584 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2585 New->isLocalExternDecl()) {
2586 // It's OK if we couldn't merge types for a local function declaraton
2587 // if either the old or new type is dependent. We'll merge the types
2588 // when we instantiate the function.
2589 return false;
2590 }
2591
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002592 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002593 }
Chris Lattner04421082008-04-08 04:40:51 +00002594
2595 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002596 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002597 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002598 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002599 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2600 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002601 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002602 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002603 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002604 // The old declaration provided a function prototype, but the
2605 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002606 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002607 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002608 OldProto->arg_type_end());
2609 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002610 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002611 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002612 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002613 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002614
2615 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002616 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002617 for (FunctionProtoType::arg_type_iterator
2618 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002619 ParamEnd = OldProto->arg_type_end();
2620 ParamType != ParamEnd; ++ParamType) {
2621 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002622 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002623 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002624 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002625 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002626 0);
John McCallfb44de92011-05-01 22:35:37 +00002627 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002628 Param->setImplicit();
2629 Params.push_back(Param);
2630 }
2631
David Blaikie4278c652011-09-21 18:16:56 +00002632 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002633 }
Douglas Gregor68719812009-02-16 18:20:44 +00002634
Richard Smithdd9459f2013-08-13 18:18:50 +00002635 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002636 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002637
Douglas Gregorc8376562009-03-06 22:43:54 +00002638 // GNU C permits a K&R definition to follow a prototype declaration
2639 // if the declared types of the parameters in the K&R definition
2640 // match the types in the prototype declaration, even when the
2641 // promoted types of the parameters from the K&R definition differ
2642 // from the types in the prototype. GCC then keeps the types from
2643 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002644 //
2645 // If a variadic prototype is followed by a non-variadic K&R definition,
2646 // the K&R definition becomes variadic. This is sort of an edge case, but
2647 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2648 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002649 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002650 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002651 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002652 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002653 SmallVector<QualType, 16> ArgTypes;
2654 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002655 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002656 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002657 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002658 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Douglas Gregorc8376562009-03-06 22:43:54 +00002660 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002661 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2662 NewProto->getResultType());
2663 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002664 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002665 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002666 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2667 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002668 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002669 NewProto->getArgType(Idx))) {
2670 ArgTypes.push_back(NewParm->getType());
2671 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002672 NewParm->getType(),
2673 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002674 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002675 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2676 Warnings.push_back(Warn);
2677 ArgTypes.push_back(NewParm->getType());
2678 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002679 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002680 }
2681
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002682 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002683 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2684 Diag(Warnings[Warn].NewParm->getLocation(),
2685 diag::ext_param_promoted_not_compatible_with_prototype)
2686 << Warnings[Warn].PromotedType
2687 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002688 if (Warnings[Warn].OldParm->getLocation().isValid())
2689 Diag(Warnings[Warn].OldParm->getLocation(),
2690 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002691 }
2692
Richard Smithdd9459f2013-08-13 18:18:50 +00002693 if (MergeTypeWithOld)
2694 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2695 OldProto->getExtProtoInfo()));
2696 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002697 }
2698
2699 // Fall through to diagnose conflicting types.
2700 }
2701
John McCall088831d2013-04-14 08:50:55 +00002702 // A function that has already been declared has been redeclared or
2703 // defined with a different type; show an appropriate diagnostic.
2704
2705 // If the previous declaration was an implicitly-generated builtin
2706 // declaration, then at the very least we should use a specialized note.
2707 unsigned BuiltinID;
2708 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2709 // If it's actually a library-defined builtin function like 'malloc'
2710 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002711 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002712 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2713 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2714 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002715
2716 // If this is a global redeclaration, just forget hereafter
2717 // about the "builtin-ness" of the function.
2718 //
2719 // Doing this for local extern declarations is problematic. If
2720 // the builtin declaration remains visible, a second invalid
2721 // local declaration will produce a hard error; if it doesn't
2722 // remain visible, a single bogus local redeclaration (which is
2723 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002724 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002725 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2726
Douglas Gregor374e1562009-03-23 17:47:24 +00002727 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002728 }
Steve Naroff837618c2008-01-16 15:01:34 +00002729
Douglas Gregorcda9c672009-02-16 17:45:42 +00002730 PrevDiag = diag::note_previous_builtin_declaration;
2731 }
2732
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002733 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002734 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002735 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002736}
2737
Douglas Gregor04495c82009-02-24 01:23:02 +00002738/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002739/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002740///
2741/// This routine handles the merging of attributes and other
2742/// properties of function declarations form the old declaration to
2743/// the new declaration, once we know that New is in fact a
2744/// redeclaration of Old.
2745///
2746/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002747bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002748 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002749 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002750 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002751
Douglas Gregor04495c82009-02-24 01:23:02 +00002752 // Merge "pure" flag.
2753 if (Old->isPure())
2754 New->setPure();
2755
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002756 // Merge "used" flag.
Eli Friedman86164e82013-09-05 00:02:25 +00002757 New->setIsUsed(Old->isUsed(false));
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002758
John McCalleca5d222011-03-02 04:00:57 +00002759 // Merge attributes from the parameters. These can mismatch with K&R
2760 // declarations.
2761 if (New->getNumParams() == Old->getNumParams())
2762 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2763 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002764 *this);
John McCalleca5d222011-03-02 04:00:57 +00002765
David Blaikie4e4d0842012-03-11 07:00:24 +00002766 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002767 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002768
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002769 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002770 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2771 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002772 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002773 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002774 New->setType(Merged);
2775
Douglas Gregor04495c82009-02-24 01:23:02 +00002776 return false;
2777}
2778
John McCallf85e1932011-06-15 23:02:42 +00002779
John McCalleca5d222011-03-02 04:00:57 +00002780void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002781 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002782
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002783 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002784 AvailabilityMergeKind MergeKind =
2785 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2786 : AMK_Override;
2787 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002788
2789 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002790 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2791 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002792 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002793 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002794 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002795 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002796
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002797 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002798}
2799
Sebastian Redl60618fa2011-03-12 11:50:43 +00002800/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2801/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002802/// emitting diagnostics as appropriate.
2803///
2804/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002805/// to here in AddInitializerToDecl. We can't check them before the initializer
2806/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002807void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2808 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002809 if (New->isInvalidDecl() || Old->isInvalidDecl())
2810 return;
2811
2812 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002813 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002814 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002815 // We don't know what the new type is until the initializer is attached.
2816 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002817 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2818 // These could still be something that needs exception specs checked.
2819 return MergeVarDeclExceptionSpecs(New, Old);
2820 }
Richard Smith34b41d92011-02-20 03:19:35 +00002821 // C++ [basic.link]p10:
2822 // [...] the types specified by all declarations referring to a given
2823 // object or function shall be identical, except that declarations for an
2824 // array object can specify array types that differ by the presence or
2825 // absence of a major array bound (8.3.4).
2826 else if (Old->getType()->isIncompleteArrayType() &&
2827 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002828 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2829 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2830 if (Context.hasSameType(OldArray->getElementType(),
2831 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002832 MergedT = New->getType();
2833 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002834 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002835 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2836 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2837 if (Context.hasSameType(OldArray->getElementType(),
2838 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002839 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002840 } else if (New->getType()->isObjCObjectPointerType() &&
2841 Old->getType()->isObjCObjectPointerType()) {
2842 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2843 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002844 }
2845 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002846 // C 6.2.7p2:
2847 // All declarations that refer to the same object or function shall have
2848 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002849 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2850 }
2851 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002852 // It's OK if we couldn't merge types if either type is dependent, for a
2853 // block-scope variable. In other cases (static data members of class
2854 // templates, variable templates, ...), we require the types to be
2855 // equivalent.
2856 // FIXME: The C++ standard doesn't say anything about this.
2857 if ((New->getType()->isDependentType() ||
2858 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2859 // If the old type was dependent, we can't merge with it, so the new type
2860 // becomes dependent for now. We'll reproduce the original type when we
2861 // instantiate the TypeSourceInfo for the variable.
2862 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2863 New->setType(Context.DependentTy);
2864 return;
2865 }
2866
2867 // FIXME: Even if this merging succeeds, some other non-visible declaration
2868 // of this variable might have an incompatible type. For instance:
2869 //
2870 // extern int arr[];
2871 // void f() { extern int arr[2]; }
2872 // void g() { extern int arr[3]; }
2873 //
2874 // Neither C nor C++ requires a diagnostic for this, but we should still try
2875 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002876 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002877 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002878 Diag(Old->getLocation(), diag::note_previous_definition);
2879 return New->setInvalidDecl();
2880 }
John McCall5b8740f2013-04-01 18:34:28 +00002881
2882 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002883 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002884 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002885 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002886}
2887
Richard Smith99a72382013-09-03 21:00:58 +00002888static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2889 LookupResult &Previous) {
2890 // C11 6.2.7p4:
2891 // For an identifier with internal or external linkage declared
2892 // in a scope in which a prior declaration of that identifier is
2893 // visible, if the prior declaration specifies internal or
2894 // external linkage, the type of the identifier at the later
2895 // declaration becomes the composite type.
2896 //
2897 // If the variable isn't visible, we do not merge with its type.
2898 if (Previous.isShadowed())
2899 return false;
2900
2901 if (S.getLangOpts().CPlusPlus) {
2902 // C++11 [dcl.array]p3:
2903 // If there is a preceding declaration of the entity in the same
2904 // scope in which the bound was specified, an omitted array bound
2905 // is taken to be the same as in that earlier declaration.
2906 return NewVD->isPreviousDeclInSameBlockScope() ||
2907 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2908 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2909 } else {
2910 // If the old declaration was function-local, don't merge with its
2911 // type unless we're in the same function.
2912 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2913 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2914 }
2915}
2916
Reid Spencer5f016e22007-07-11 17:01:13 +00002917/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2918/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2919/// situation, merging decls or emitting diagnostics as appropriate.
2920///
Mike Stump1eb44332009-09-09 15:08:12 +00002921/// Tentative definition rules (C99 6.9.2p2) are checked by
2922/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002923/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00002924///
Richard Smith99a72382013-09-03 21:00:58 +00002925void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00002926 // If the new decl is already invalid, don't do any other checking.
2927 if (New->isInvalidDecl())
2928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Larisse Voufo4a919892013-08-14 03:09:19 +00002930 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00002931 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00002932 if (Previous.isSingleResult() &&
2933 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00002934 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00002935 Old = Old->getDescribedVarTemplate() ? Old : 0;
2936 else
2937 Old = Old->getDescribedVarTemplate() ? 0 : Old;
2938 }
2939 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002940 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002941 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00002942 Diag(Previous.getRepresentativeDecl()->getLocation(),
2943 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002944 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 }
Chris Lattnerddee4232008-03-03 03:28:21 +00002946
Rafael Espindola90cc3902013-04-15 12:49:13 +00002947 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2948 return;
2949
Douglas Gregor7f6ff022010-08-30 14:32:14 +00002950 // C++ [class.mem]p1:
2951 // A member shall not be declared twice in the member-specification [...]
2952 //
2953 // Here, we need only consider static data members.
2954 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2955 Diag(New->getLocation(), diag::err_duplicate_member)
2956 << New->getIdentifier();
2957 Diag(Old->getLocation(), diag::note_previous_declaration);
2958 New->setInvalidDecl();
2959 }
2960
Douglas Gregor27c6da22012-01-01 20:30:41 +00002961 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00002962 // Warn if an already-declared variable is made a weak_import in a subsequent
2963 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00002964 if (New->getAttr<WeakImportAttr>() &&
2965 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00002966 !Old->getAttr<WeakImportAttr>()) {
2967 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2968 Diag(Old->getLocation(), diag::note_previous_definition);
2969 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00002970 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00002971 }
Chris Lattnerddee4232008-03-03 03:28:21 +00002972
Richard Smith34b41d92011-02-20 03:19:35 +00002973 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00002974 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
2975
Richard Smith34b41d92011-02-20 03:19:35 +00002976 if (New->isInvalidDecl())
2977 return;
Douglas Gregor656de632009-03-11 23:52:16 +00002978
Rafael Espindolaea4b1112013-04-04 21:21:25 +00002979 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00002980 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00002981 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002982 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002983 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002984 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002985 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00002986 }
Mike Stump1eb44332009-09-09 15:08:12 +00002987 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00002988 // For an identifier declared with the storage-class specifier
2989 // extern in a scope in which a prior declaration of that
2990 // identifier is visible,23) if the prior declaration specifies
2991 // internal or external linkage, the linkage of the identifier at
2992 // the later declaration is the same as the linkage specified at
2993 // the prior declaration. If no prior declaration is visible, or
2994 // if the prior declaration specifies no linkage, then the
2995 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00002996 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00002997 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002998 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00002999 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003000 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003002 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003003 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003004 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003005
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003006 // Check if extern is followed by non-extern and vice-versa.
3007 if (New->hasExternalStorage() &&
3008 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3009 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3010 Diag(Old->getLocation(), diag::note_previous_definition);
3011 return New->setInvalidDecl();
3012 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003013 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3014 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003015 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3016 Diag(Old->getLocation(), diag::note_previous_definition);
3017 return New->setInvalidDecl();
3018 }
3019
Steve Naroff094cefb2008-09-17 14:05:40 +00003020 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003022 // FIXME: The test for external storage here seems wrong? We still
3023 // need to check for mismatches.
3024 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003025 // Don't complain about out-of-line definitions of static members.
3026 !(Old->getLexicalDeclContext()->isRecord() &&
3027 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003028 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003029 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003030 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003031 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003032
Richard Smith38afbc72013-04-13 02:43:54 +00003033 if (New->getTLSKind() != Old->getTLSKind()) {
3034 if (!Old->getTLSKind()) {
3035 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3036 Diag(Old->getLocation(), diag::note_previous_declaration);
3037 } else if (!New->getTLSKind()) {
3038 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3039 Diag(Old->getLocation(), diag::note_previous_declaration);
3040 } else {
3041 // Do not allow redeclaration to change the variable between requiring
3042 // static and dynamic initialization.
3043 // FIXME: GCC allows this, but uses the TLS keyword on the first
3044 // declaration to determine the kind. Do we need to be compatible here?
3045 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3046 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3047 Diag(Old->getLocation(), diag::note_previous_declaration);
3048 }
Eli Friedman63054b32009-04-19 20:27:55 +00003049 }
3050
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003051 // C++ doesn't have tentative definitions, so go right ahead and check here.
3052 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003053 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003054 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003055 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003056 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003057 Diag(Def->getLocation(), diag::note_previous_definition);
3058 New->setInvalidDecl();
3059 return;
3060 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003061
Rafael Espindola950fee22013-02-14 01:18:37 +00003062 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003063 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3064 Diag(Old->getLocation(), diag::note_previous_definition);
3065 New->setInvalidDecl();
3066 return;
3067 }
3068
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003069 // Merge "used" flag.
Eli Friedman86164e82013-09-05 00:02:25 +00003070 New->setIsUsed(Old->isUsed(false));
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003071
Douglas Gregor275a3692009-03-10 23:43:53 +00003072 // Keep a chain of previous declarations.
3073 New->setPreviousDeclaration(Old);
John McCall46460a62010-01-20 21:53:11 +00003074
3075 // Inherit access appropriately.
3076 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003077
3078 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3079 if (New->isStaticDataMember() && New->isOutOfLine())
3080 VTD->setAccess(New->getAccess());
3081 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003082}
3083
3084/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3085/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003086Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003087 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003088 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003089}
3090
Eli Friedman5e867c82013-07-10 00:30:46 +00003091static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003092 if (!S.Context.getLangOpts().CPlusPlus)
3093 return;
3094
Eli Friedman5e867c82013-07-10 00:30:46 +00003095 if (isa<CXXRecordDecl>(Tag->getParent())) {
3096 // If this tag is the direct child of a class, number it if
3097 // it is anonymous.
3098 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3099 return;
3100 MangleNumberingContext &MCtx =
3101 S.Context.getManglingNumberContext(Tag->getParent());
3102 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3103 return;
3104 }
3105
3106 // If this tag isn't a direct child of a class, number it if it is local.
3107 Decl *ManglingContextDecl;
3108 if (MangleNumberingContext *MCtx =
3109 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3110 ManglingContextDecl)) {
3111 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3112 }
3113}
3114
Chandler Carruth0f4be742011-05-03 18:35:10 +00003115/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003116/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003117/// parameters to cope with template friend declarations.
3118Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3119 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003120 MultiTemplateParamsArg TemplateParams,
3121 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003122 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003123 TagDecl *Tag = 0;
3124 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3125 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003126 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003127 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003128 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003129 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003130
3131 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003132 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003133
John McCall67d1a672009-08-06 02:15:43 +00003134 // Note that the above type specs guarantee that the
3135 // type rep is a Decl, whereas in many of the others
3136 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003137 if (isa<TagDecl>(TagD))
3138 Tag = cast<TagDecl>(TagD);
3139 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3140 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003141 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003142
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003143 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003144 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003145 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003146 if (Tag->isInvalidDecl())
3147 return Tag;
3148 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003149
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003150 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3151 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3152 // or incomplete types shall not be restrict-qualified."
3153 if (TypeQuals & DeclSpec::TQ_restrict)
3154 Diag(DS.getRestrictSpecLoc(),
3155 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3156 << DS.getSourceRange();
3157 }
3158
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003159 if (DS.isConstexprSpecified()) {
3160 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3161 // and definitions of functions and variables.
3162 if (Tag)
3163 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3164 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3165 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003166 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3167 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003168 else
3169 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3170 // Don't emit warnings after this error.
3171 return TagD;
3172 }
3173
Richard Smithc7f81162013-03-18 22:52:47 +00003174 DiagnoseFunctionSpecifiers(DS);
3175
Douglas Gregord85bea22009-09-26 06:47:28 +00003176 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003177 // If we're dealing with a decl but not a TagDecl, assume that
3178 // whatever routines created it handled the friendship aspect.
3179 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003180 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003181 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003182 }
John McCallac4df242011-03-22 23:00:04 +00003183
Richard Smithc7f81162013-03-18 22:52:47 +00003184 CXXScopeSpec &SS = DS.getTypeSpecScope();
3185 bool IsExplicitSpecialization =
3186 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3187 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3188 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3189 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3190 // nested-name-specifier unless it is an explicit instantiation
3191 // or an explicit specialization.
3192 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3193 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3194 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3195 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3196 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3197 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3198 << SS.getRange();
3199 return 0;
3200 }
3201
3202 // Track whether this decl-specifier declares anything.
3203 bool DeclaresAnything = true;
3204
3205 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003206 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003207 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003208 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003209 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003210 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003211 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003212
Richard Smithc7f81162013-03-18 22:52:47 +00003213 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003214 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003215 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003216
Richard Smithc7f81162013-03-18 22:52:47 +00003217 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003218 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003219 CurContext->isRecord() &&
3220 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3221 // Handle 2 kinds of anonymous struct:
3222 // struct STRUCT;
3223 // and
3224 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3225 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003226 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003227 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3228 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003229 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003230 << DS.getSourceRange();
3231 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3232 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003233 }
Richard Smithc7f81162013-03-18 22:52:47 +00003234
3235 // Skip all the checks below if we have a type error.
3236 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3237 (TagD && TagD->isInvalidDecl()))
3238 return TagD;
3239
3240 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003241 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3242 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3243 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003244 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3245 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003246
John McCallac4df242011-03-22 23:00:04 +00003247 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003248 // Customize diagnostic for a typedef missing a name.
3249 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003250 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003251 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003252 else
3253 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003254 }
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Richard Smithc7f81162013-03-18 22:52:47 +00003256 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003257 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3258 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3259 << Tag->getTagKind()
3260 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3261
Richard Smithc7f81162013-03-18 22:52:47 +00003262 ActOnDocumentableDecl(TagD);
3263
3264 // C 6.7/2:
3265 // A declaration [...] shall declare at least a declarator [...], a tag,
3266 // or the members of an enumeration.
3267 // C++ [dcl.dcl]p3:
3268 // [If there are no declarators], and except for the declaration of an
3269 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3270 // names into the program, or shall redeclare a name introduced by a
3271 // previous declaration.
3272 if (!DeclaresAnything) {
3273 // In C, we allow this as a (popular) extension / bug. Don't bother
3274 // producing further diagnostics for redundant qualifiers after this.
3275 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3276 return TagD;
3277 }
3278
3279 // C++ [dcl.stc]p1:
3280 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3281 // init-declarator-list of the declaration shall not be empty.
3282 // C++ [dcl.fct.spec]p1:
3283 // If a cv-qualifier appears in a decl-specifier-seq, the
3284 // init-declarator-list of the declaration shall not be empty.
3285 //
3286 // Spurious qualifiers here appear to be valid in C.
3287 unsigned DiagID = diag::warn_standalone_specifier;
3288 if (getLangOpts().CPlusPlus)
3289 DiagID = diag::ext_standalone_specifier;
3290
3291 // Note that a linkage-specification sets a storage class, but
3292 // 'extern "C" struct foo;' is actually valid and not theoretically
3293 // useless.
3294 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3295 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3296 Diag(DS.getStorageClassSpecLoc(), DiagID)
3297 << DeclSpec::getSpecifierName(SCS);
3298
Richard Smithec642442013-04-12 22:46:28 +00003299 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3300 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3301 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003302 if (DS.getTypeQualifiers()) {
3303 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3304 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3305 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3306 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3307 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003308 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3309 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003310 }
3311
Eli Friedmanfc038e92011-12-17 00:36:09 +00003312 // Warn about ignored type attributes, for example:
3313 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003314 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003315 if (!DS.getAttributes().empty()) {
3316 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3317 if (TypeSpecType == DeclSpec::TST_class ||
3318 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003319 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003320 TypeSpecType == DeclSpec::TST_union ||
3321 TypeSpecType == DeclSpec::TST_enum) {
3322 AttributeList* attrs = DS.getAttributes().getList();
3323 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003324 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003325 << attrs->getName()
3326 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3327 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003328 TypeSpecType == DeclSpec::TST_union ? 2 :
3329 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003330 attrs = attrs->getNext();
3331 }
3332 }
3333 }
John McCallac4df242011-03-22 23:00:04 +00003334
John McCalld226f652010-08-21 09:40:31 +00003335 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003336}
3337
John McCall1d7c5282009-12-18 10:40:03 +00003338/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003339/// check if there's an existing declaration that can't be overloaded.
3340///
3341/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003342static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3343 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003344 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003345 DeclarationName Name,
3346 SourceLocation NameLoc,
3347 unsigned diagnostic) {
3348 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3349 Sema::ForRedeclaration);
3350 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003351
John McCall1d7c5282009-12-18 10:40:03 +00003352 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003353 return false;
3354
3355 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003356 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003357 assert(PrevDecl && "Expected a non-null Decl");
3358
3359 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3360 return false;
John McCall68263142009-11-18 22:49:29 +00003361
John McCall1d7c5282009-12-18 10:40:03 +00003362 SemaRef.Diag(NameLoc, diagnostic) << Name;
3363 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003364
3365 return true;
3366}
3367
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003368/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3369/// anonymous struct or union AnonRecord into the owning context Owner
3370/// and scope S. This routine will be invoked just after we realize
3371/// that an unnamed union or struct is actually an anonymous union or
3372/// struct, e.g.,
3373///
3374/// @code
3375/// union {
3376/// int i;
3377/// float f;
3378/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3379/// // f into the surrounding scope.x
3380/// @endcode
3381///
3382/// This routine is recursive, injecting the names of nested anonymous
3383/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003384static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003385 DeclContext *Owner,
3386 RecordDecl *AnonRecord,
3387 AccessSpecifier AS,
3388 SmallVectorImpl<NamedDecl *> &Chaining,
3389 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003390 unsigned diagKind
3391 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3392 : diag::err_anonymous_struct_member_redecl;
3393
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003394 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003395
3396 // Look every FieldDecl and IndirectFieldDecl with a name.
3397 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3398 DEnd = AnonRecord->decls_end();
3399 D != DEnd; ++D) {
3400 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3401 cast<NamedDecl>(*D)->getDeclName()) {
3402 ValueDecl *VD = cast<ValueDecl>(*D);
3403 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3404 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003405 // C++ [class.union]p2:
3406 // The names of the members of an anonymous union shall be
3407 // distinct from the names of any other entity in the
3408 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003409 Invalid = true;
3410 } else {
3411 // C++ [class.union]p2:
3412 // For the purpose of name lookup, after the anonymous union
3413 // definition, the members of the anonymous union are
3414 // considered to have been defined in the scope in which the
3415 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003416 unsigned OldChainingSize = Chaining.size();
3417 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3418 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3419 PE = IF->chain_end(); PI != PE; ++PI)
3420 Chaining.push_back(*PI);
3421 else
3422 Chaining.push_back(VD);
3423
Francois Pichet87c2e122010-11-21 06:08:52 +00003424 assert(Chaining.size() >= 2);
3425 NamedDecl **NamedChain =
3426 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3427 for (unsigned i = 0; i < Chaining.size(); i++)
3428 NamedChain[i] = Chaining[i];
3429
3430 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003431 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3432 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003433 NamedChain, Chaining.size());
3434
3435 IndirectField->setAccess(AS);
3436 IndirectField->setImplicit();
3437 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003438
3439 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003440 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003441
Francois Pichet8e161ed2010-11-23 06:07:27 +00003442 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003443 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003444 }
3445 }
3446
3447 return Invalid;
3448}
3449
Douglas Gregor16573fa2010-04-19 22:54:31 +00003450/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3451/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003452/// illegal input values are mapped to SC_None.
3453static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003454StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3455 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3456 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3457 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003458 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003459 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003460 case DeclSpec::SCS_extern:
3461 if (DS.isExternInLinkageSpec())
3462 return SC_None;
3463 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003464 case DeclSpec::SCS_static: return SC_Static;
3465 case DeclSpec::SCS_auto: return SC_Auto;
3466 case DeclSpec::SCS_register: return SC_Register;
3467 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003468 // Illegal SCSs map to None: error reporting is up to the caller.
3469 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003470 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003471 }
3472 llvm_unreachable("unknown storage class specifier");
3473}
3474
Francois Pichet8e161ed2010-11-23 06:07:27 +00003475/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003476/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003477/// (C++ [class.union]) and a C11 feature; anonymous structures
3478/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003479Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3480 AccessSpecifier AS,
3481 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003482 DeclContext *Owner = Record->getDeclContext();
3483
3484 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003485 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003486 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003487 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003488 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003489 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003490 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003491
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003492 // C and C++ require different kinds of checks for anonymous
3493 // structs/unions.
3494 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003495 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003496 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003497 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003498 if (Record->isUnion()) {
3499 // C++ [class.union]p6:
3500 // Anonymous unions declared in a named namespace or in the
3501 // global namespace shall be declared static.
3502 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3503 (isa<TranslationUnitDecl>(Owner) ||
3504 (isa<NamespaceDecl>(Owner) &&
3505 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003506 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3507 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003508
3509 // Recover by adding 'static'.
3510 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3511 PrevSpec, DiagID);
3512 }
3513 // C++ [class.union]p6:
3514 // A storage class is not allowed in a declaration of an
3515 // anonymous union in a class scope.
3516 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3517 isa<RecordDecl>(Owner)) {
3518 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003519 diag::err_anonymous_union_with_storage_spec)
3520 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003521
3522 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003523 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3524 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003525 PrevSpec, DiagID);
3526 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003527 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003528
Douglas Gregor7604f642011-05-09 23:05:33 +00003529 // Ignore const/volatile/restrict qualifiers.
3530 if (DS.getTypeQualifiers()) {
3531 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3532 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003533 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003534 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3535 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003536 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003537 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003538 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003539 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3540 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003541 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003542 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003543 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003544 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003545 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3546 Diag(DS.getAtomicSpecLoc(),
3547 diag::ext_anonymous_struct_union_qualified)
3548 << Record->isUnion() << "_Atomic"
3549 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003550
3551 DS.ClearTypeQualifiers();
3552 }
3553
Mike Stump1eb44332009-09-09 15:08:12 +00003554 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003555 // The member-specification of an anonymous union shall only
3556 // define non-static data members. [Note: nested types and
3557 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003558 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3559 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003560 Mem != MemEnd; ++Mem) {
3561 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3562 // C++ [class.union]p3:
3563 // An anonymous union shall not have private or protected
3564 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003565 assert(FD->getAccess() != AS_none);
3566 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003567 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3568 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3569 Invalid = true;
3570 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003571
Sean Huntcf34e752011-05-16 22:41:40 +00003572 // C++ [class.union]p1
3573 // An object of a class with a non-trivial constructor, a non-trivial
3574 // copy constructor, a non-trivial destructor, or a non-trivial copy
3575 // assignment operator cannot be a member of a union, nor can an
3576 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003577 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003578 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003579 } else if ((*Mem)->isImplicit()) {
3580 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003581 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3582 // This is a type that showed up in an
3583 // elaborated-type-specifier inside the anonymous struct or
3584 // union, but which actually declares a type outside of the
3585 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003586 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3587 if (!MemRecord->isAnonymousStructOrUnion() &&
3588 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003589 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003590 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00003591 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3592 << (int)Record->isUnion();
3593 else {
3594 // This is a nested type declaration.
3595 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3596 << (int)Record->isUnion();
3597 Invalid = true;
3598 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003599 } else {
3600 // This is an anonymous type definition within another anonymous type.
3601 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3602 // not part of standard C++.
3603 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003604 diag::ext_anonymous_record_with_anonymous_type)
3605 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003606 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003607 } else if (isa<AccessSpecDecl>(*Mem)) {
3608 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003609 } else {
3610 // We have something that isn't a non-static data
3611 // member. Complain about it.
3612 unsigned DK = diag::err_anonymous_record_bad_member;
3613 if (isa<TypeDecl>(*Mem))
3614 DK = diag::err_anonymous_record_with_type;
3615 else if (isa<FunctionDecl>(*Mem))
3616 DK = diag::err_anonymous_record_with_function;
3617 else if (isa<VarDecl>(*Mem))
3618 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003619
3620 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003621 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003622 DK == diag::err_anonymous_record_with_type)
3623 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003624 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003625 else {
3626 Diag((*Mem)->getLocation(), DK)
3627 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003628 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003629 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003630 }
3631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003633
3634 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003635 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003636 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003637 Invalid = true;
3638 }
3639
John McCalleb692e02009-10-22 23:31:08 +00003640 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003641 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003642 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003643 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003644
Mike Stump1eb44332009-09-09 15:08:12 +00003645 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003646 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003647 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003648 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003649 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003650 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003651 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003652 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003653 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003654 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003655 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003656 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003657 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003658 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003659 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003660 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003661 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003662 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003663 // mutable can only appear on non-static class members, so it's always
3664 // an error here
3665 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3666 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003667 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003668 }
3669
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003670 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003671 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003672 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003673 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003674 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003675
3676 // Default-initialize the implicit variable. This initialization will be
3677 // trivial in almost all cases, except if a union member has an in-class
3678 // initializer:
3679 // union { int n = 0; };
3680 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003681 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003682 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003683
3684 // Add the anonymous struct/union object to the current
3685 // context. We'll be referencing this object when we refer to one of
3686 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003687 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003688
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003689 // Inject the members of the anonymous struct/union into the owning
3690 // context and into the identifier resolver chain for name lookup
3691 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003692 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003693 Chain.push_back(Anon);
3694
Francois Pichet8e161ed2010-11-23 06:07:27 +00003695 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3696 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003697 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003698
3699 // Mark this as an anonymous struct/union type. Note that we do not
3700 // do this until after we have already checked and injected the
3701 // members of this anonymous struct/union type, because otherwise
3702 // the members could be injected twice: once by DeclContext when it
3703 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003704 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003705 Record->setAnonymousStructOrUnion(true);
3706
3707 if (Invalid)
3708 Anon->setInvalidDecl();
3709
John McCalld226f652010-08-21 09:40:31 +00003710 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003711}
3712
Francois Pichet8e161ed2010-11-23 06:07:27 +00003713/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3714/// Microsoft C anonymous structure.
3715/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3716/// Example:
3717///
3718/// struct A { int a; };
3719/// struct B { struct A; int b; };
3720///
3721/// void foo() {
3722/// B var;
3723/// var.a = 3;
3724/// }
3725///
3726Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3727 RecordDecl *Record) {
3728
3729 // If there is no Record, get the record via the typedef.
3730 if (!Record)
3731 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3732
3733 // Mock up a declarator.
3734 Declarator Dc(DS, Declarator::TypeNameContext);
3735 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3736 assert(TInfo && "couldn't build declarator info for anonymous struct");
3737
3738 // Create a declaration for this anonymous struct.
3739 NamedDecl* Anon = FieldDecl::Create(Context,
3740 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003741 DS.getLocStart(),
3742 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003743 /*IdentifierInfo=*/0,
3744 Context.getTypeDeclType(Record),
3745 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003746 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003747 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003748 Anon->setImplicit();
3749
3750 // Add the anonymous struct object to the current context.
3751 CurContext->addDecl(Anon);
3752
3753 // Inject the members of the anonymous struct into the current
3754 // context and into the identifier resolver chain for name lookup
3755 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003756 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003757 Chain.push_back(Anon);
3758
Nico Weberee625af2012-02-01 00:41:00 +00003759 RecordDecl *RecordDef = Record->getDefinition();
3760 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3761 RecordDef, AS_none,
3762 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003763 Anon->setInvalidDecl();
3764
3765 return Anon;
3766}
Steve Narofff0090632007-09-02 02:04:30 +00003767
Douglas Gregor10bd3682008-11-17 22:58:34 +00003768/// GetNameForDeclarator - Determine the full declaration name for the
3769/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003770DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003771 return GetNameFromUnqualifiedId(D.getName());
3772}
3773
Abramo Bagnara25777432010-08-11 22:01:17 +00003774/// \brief Retrieves the declaration name from a parsed unqualified-id.
3775DeclarationNameInfo
3776Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3777 DeclarationNameInfo NameInfo;
3778 NameInfo.setLoc(Name.StartLocation);
3779
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003780 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003781
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003782 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003783 case UnqualifiedId::IK_Identifier:
3784 NameInfo.setName(Name.Identifier);
3785 NameInfo.setLoc(Name.StartLocation);
3786 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003787
Abramo Bagnara25777432010-08-11 22:01:17 +00003788 case UnqualifiedId::IK_OperatorFunctionId:
3789 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3790 Name.OperatorFunctionId.Operator));
3791 NameInfo.setLoc(Name.StartLocation);
3792 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3793 = Name.OperatorFunctionId.SymbolLocations[0];
3794 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3795 = Name.EndLocation.getRawEncoding();
3796 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003797
Abramo Bagnara25777432010-08-11 22:01:17 +00003798 case UnqualifiedId::IK_LiteralOperatorId:
3799 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3800 Name.Identifier));
3801 NameInfo.setLoc(Name.StartLocation);
3802 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3803 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003804
Abramo Bagnara25777432010-08-11 22:01:17 +00003805 case UnqualifiedId::IK_ConversionFunctionId: {
3806 TypeSourceInfo *TInfo;
3807 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3808 if (Ty.isNull())
3809 return DeclarationNameInfo();
3810 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3811 Context.getCanonicalType(Ty)));
3812 NameInfo.setLoc(Name.StartLocation);
3813 NameInfo.setNamedTypeInfo(TInfo);
3814 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003815 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003816
3817 case UnqualifiedId::IK_ConstructorName: {
3818 TypeSourceInfo *TInfo;
3819 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3820 if (Ty.isNull())
3821 return DeclarationNameInfo();
3822 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3823 Context.getCanonicalType(Ty)));
3824 NameInfo.setLoc(Name.StartLocation);
3825 NameInfo.setNamedTypeInfo(TInfo);
3826 return NameInfo;
3827 }
3828
3829 case UnqualifiedId::IK_ConstructorTemplateId: {
3830 // In well-formed code, we can only have a constructor
3831 // template-id that refers to the current context, so go there
3832 // to find the actual type being constructed.
3833 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3834 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3835 return DeclarationNameInfo();
3836
3837 // Determine the type of the class being constructed.
3838 QualType CurClassType = Context.getTypeDeclType(CurClass);
3839
3840 // FIXME: Check two things: that the template-id names the same type as
3841 // CurClassType, and that the template-id does not occur when the name
3842 // was qualified.
3843
3844 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3845 Context.getCanonicalType(CurClassType)));
3846 NameInfo.setLoc(Name.StartLocation);
3847 // FIXME: should we retrieve TypeSourceInfo?
3848 NameInfo.setNamedTypeInfo(0);
3849 return NameInfo;
3850 }
3851
3852 case UnqualifiedId::IK_DestructorName: {
3853 TypeSourceInfo *TInfo;
3854 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3855 if (Ty.isNull())
3856 return DeclarationNameInfo();
3857 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3858 Context.getCanonicalType(Ty)));
3859 NameInfo.setLoc(Name.StartLocation);
3860 NameInfo.setNamedTypeInfo(TInfo);
3861 return NameInfo;
3862 }
3863
3864 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003865 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003866 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3867 return Context.getNameForTemplate(TName, TNameLoc);
3868 }
3869
3870 } // switch (Name.getKind())
3871
David Blaikieb219cfc2011-09-23 05:06:16 +00003872 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003873}
3874
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003875static QualType getCoreType(QualType Ty) {
3876 do {
3877 if (Ty->isPointerType() || Ty->isReferenceType())
3878 Ty = Ty->getPointeeType();
3879 else if (Ty->isArrayType())
3880 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3881 else
3882 return Ty.withoutLocalFastQualifiers();
3883 } while (true);
3884}
3885
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003886/// hasSimilarParameters - Determine whether the C++ functions Declaration
3887/// and Definition have "nearly" matching parameters. This heuristic is
3888/// used to improve diagnostics in the case where an out-of-line function
3889/// definition doesn't match any declaration within the class or namespace.
3890/// Also sets Params to the list of indices to the parameters that differ
3891/// between the declaration and the definition. If hasSimilarParameters
3892/// returns true and Params is empty, then all of the parameters match.
3893static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003894 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003895 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003896 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003897 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003898 if (Declaration->param_size() != Definition->param_size())
3899 return false;
3900 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3901 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3902 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3903
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003904 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003905 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003906 continue;
3907
3908 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3909 QualType DefParamBaseTy = getCoreType(DefParamTy);
3910 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3911 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3912
3913 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3914 (DeclTyName && DeclTyName == DefTyName))
3915 Params.push_back(Idx);
3916 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003917 return false;
3918 }
3919
3920 return true;
3921}
3922
John McCall63b43852010-04-29 23:50:39 +00003923/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3924/// declarator needs to be rebuilt in the current instantiation.
3925/// Any bits of declarator which appear before the name are valid for
3926/// consideration here. That's specifically the type in the decl spec
3927/// and the base type in any member-pointer chunks.
3928static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3929 DeclarationName Name) {
3930 // The types we specifically need to rebuild are:
3931 // - typenames, typeofs, and decltypes
3932 // - types which will become injected class names
3933 // Of course, we also need to rebuild any type referencing such a
3934 // type. It's safest to just say "dependent", but we call out a
3935 // few cases here.
3936
3937 DeclSpec &DS = D.getMutableDeclSpec();
3938 switch (DS.getTypeSpecType()) {
3939 case DeclSpec::TST_typename:
3940 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00003941 case DeclSpec::TST_underlyingType:
3942 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00003943 // Grab the type from the parser.
3944 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00003945 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00003946 if (T.isNull() || !T->isDependentType()) break;
3947
3948 // Make sure there's a type source info. This isn't really much
3949 // of a waste; most dependent types should have type source info
3950 // attached already.
3951 if (!TSI)
3952 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3953
3954 // Rebuild the type in the current instantiation.
3955 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3956 if (!TSI) return true;
3957
3958 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00003959 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3960 DS.UpdateTypeRep(LocType);
3961 break;
3962 }
3963
Richard Smithc4a83912012-10-01 20:35:07 +00003964 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00003965 case DeclSpec::TST_typeofExpr: {
3966 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00003967 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00003968 if (Result.isInvalid()) return true;
3969 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00003970 break;
3971 }
3972
3973 default:
3974 // Nothing to do for these decl specs.
3975 break;
3976 }
3977
3978 // It doesn't matter what order we do this in.
3979 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3980 DeclaratorChunk &Chunk = D.getTypeObject(I);
3981
3982 // The only type information in the declarator which can come
3983 // before the declaration name is the base type of a member
3984 // pointer.
3985 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3986 continue;
3987
3988 // Rebuild the scope specifier in-place.
3989 CXXScopeSpec &SS = Chunk.Mem.Scope();
3990 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3991 return true;
3992 }
3993
3994 return false;
3995}
3996
Anders Carlsson3242ee02011-07-04 16:28:17 +00003997Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00003998 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003999 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004000
4001 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004002 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004003 Dcl->setTopLevelDeclInObjCContainer();
4004
4005 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004006}
4007
Richard Smith162e1c12011-04-15 14:24:37 +00004008/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4009/// If T is the name of a class, then each of the following shall have a
4010/// name different from T:
4011/// - every static data member of class T;
4012/// - every member function of class T
4013/// - every member of class T that is itself a type;
4014/// \returns true if the declaration name violates these rules.
4015bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4016 DeclarationNameInfo NameInfo) {
4017 DeclarationName Name = NameInfo.getName();
4018
4019 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4020 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4021 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4022 return true;
4023 }
4024
4025 return false;
4026}
Douglas Gregor42acead2012-03-17 23:06:31 +00004027
Douglas Gregor69605872012-03-28 16:01:27 +00004028/// \brief Diagnose a declaration whose declarator-id has the given
4029/// nested-name-specifier.
4030///
4031/// \param SS The nested-name-specifier of the declarator-id.
4032///
4033/// \param DC The declaration context to which the nested-name-specifier
4034/// resolves.
4035///
4036/// \param Name The name of the entity being declared.
4037///
4038/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004039///
4040/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004041bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004042 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004043 SourceLocation Loc) {
4044 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004045 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004046 Cur = Cur->getParent();
4047
4048 // C++ [dcl.meaning]p1:
4049 // A declarator-id shall not be qualified except for the definition
4050 // of a member function (9.3) or static data member (9.4) outside of
4051 // its class, the definition or explicit instantiation of a function
4052 // or variable member of a namespace outside of its namespace, or the
4053 // definition of an explicit specialization outside of its namespace,
4054 // or the declaration of a friend function that is a member of
4055 // another class or namespace (11.3). [...]
4056
4057 // The user provided a superfluous scope specifier that refers back to the
4058 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004059 //
4060 // class X {
4061 // void X::f();
4062 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004063 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004064 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4065 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004066 << Name << FixItHint::CreateRemoval(SS.getRange());
4067 SS.clear();
4068 return false;
4069 }
Douglas Gregor69605872012-03-28 16:01:27 +00004070
4071 // Check whether the qualifying scope encloses the scope of the original
4072 // declaration.
4073 if (!Cur->Encloses(DC)) {
4074 if (Cur->isRecord())
4075 Diag(Loc, diag::err_member_qualification)
4076 << Name << SS.getRange();
4077 else if (isa<TranslationUnitDecl>(DC))
4078 Diag(Loc, diag::err_invalid_declarator_global_scope)
4079 << Name << SS.getRange();
4080 else if (isa<FunctionDecl>(Cur))
4081 Diag(Loc, diag::err_invalid_declarator_in_function)
4082 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004083 else if (isa<BlockDecl>(Cur))
4084 Diag(Loc, diag::err_invalid_declarator_in_block)
4085 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004086 else
4087 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004088 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004089
Douglas Gregor42acead2012-03-17 23:06:31 +00004090 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004091 }
4092
4093 if (Cur->isRecord()) {
4094 // Cannot qualify members within a class.
4095 Diag(Loc, diag::err_member_qualification)
4096 << Name << SS.getRange();
4097 SS.clear();
4098
4099 // C++ constructors and destructors with incorrect scopes can break
4100 // our AST invariants by having the wrong underlying types. If
4101 // that's the case, then drop this declaration entirely.
4102 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4103 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4104 !Context.hasSameType(Name.getCXXNameType(),
4105 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4106 return true;
4107
4108 return false;
4109 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004110
Douglas Gregor69605872012-03-28 16:01:27 +00004111 // C++11 [dcl.meaning]p1:
4112 // [...] "The nested-name-specifier of the qualified declarator-id shall
4113 // not begin with a decltype-specifer"
4114 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4115 while (SpecLoc.getPrefix())
4116 SpecLoc = SpecLoc.getPrefix();
4117 if (dyn_cast_or_null<DecltypeType>(
4118 SpecLoc.getNestedNameSpecifier()->getAsType()))
4119 Diag(Loc, diag::err_decltype_in_declarator)
4120 << SpecLoc.getTypeLoc().getSourceRange();
4121
Douglas Gregor42acead2012-03-17 23:06:31 +00004122 return false;
4123}
4124
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004125NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4126 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004127 // TODO: consider using NameInfo for diagnostic.
4128 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4129 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004130
Chris Lattnere80a59c2007-07-25 00:24:17 +00004131 // All of these full declarators require an identifier. If it doesn't have
4132 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004133 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004134 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004135 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004136 diag::err_declarator_need_ident)
4137 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004138 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004139 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4140 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Chris Lattner31e05722007-08-26 06:24:45 +00004142 // The scope passed in may not be a decl scope. Zip up the scope tree until
4143 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004144 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004145 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004146 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004147
John McCall63b43852010-04-29 23:50:39 +00004148 DeclContext *DC = CurContext;
4149 if (D.getCXXScopeSpec().isInvalid())
4150 D.setInvalidType();
4151 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004152 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4153 UPPC_DeclarationQualifier))
4154 return 0;
4155
John McCall63b43852010-04-29 23:50:39 +00004156 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4157 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4158 if (!DC) {
4159 // If we could not compute the declaration context, it's because the
4160 // declaration context is dependent but does not refer to a class,
4161 // class template, or class template partial specialization. Complain
4162 // and return early, to avoid the coming semantic disaster.
4163 Diag(D.getIdentifierLoc(),
4164 diag::err_template_qualified_declarator_no_match)
4165 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4166 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004167 return 0;
John McCall63b43852010-04-29 23:50:39 +00004168 }
John McCall63b43852010-04-29 23:50:39 +00004169 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004170
John McCall63b43852010-04-29 23:50:39 +00004171 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004172 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004173 return 0;
John McCall63b43852010-04-29 23:50:39 +00004174
Douglas Gregor69605872012-03-28 16:01:27 +00004175 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4176 Diag(D.getIdentifierLoc(),
4177 diag::err_member_def_undefined_record)
4178 << Name << DC << D.getCXXScopeSpec().getRange();
4179 D.setInvalidType();
4180 } else if (!D.getDeclSpec().isFriendSpecified()) {
4181 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4182 Name, D.getIdentifierLoc())) {
4183 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004184 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004185
4186 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004187 }
John McCall63b43852010-04-29 23:50:39 +00004188 }
4189
4190 // Check whether we need to rebuild the type of the given
4191 // declaration in the current instantiation.
4192 if (EnteringContext && IsDependentContext &&
4193 TemplateParamLists.size() != 0) {
4194 ContextRAII SavedContext(*this, DC);
4195 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4196 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004197 }
4198 }
Richard Smith162e1c12011-04-15 14:24:37 +00004199
4200 if (DiagnoseClassNameShadow(DC, NameInfo))
4201 // If this is a typedef, we'll end up spewing multiple diagnostics.
4202 // Just return early; it's safer.
4203 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4204 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004205
John McCallbf1a0282010-06-04 23:28:52 +00004206 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4207 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004208
Douglas Gregord0937222010-12-13 22:49:22 +00004209 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4210 UPPC_DeclarationType))
4211 D.setInvalidType();
4212
Abramo Bagnara25777432010-08-11 22:01:17 +00004213 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004214 ForRedeclaration);
4215
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004216 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004217 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004218 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004219 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004220
4221 // If the declaration we're planning to build will be a function
4222 // or object with linkage, then look for another declaration with
4223 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004224 //
4225 // If the declaration we're planning to build will be declared with
4226 // external linkage in the translation unit, create any builtin with
4227 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004228 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4229 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004230 else if (CurContext->isFunctionOrMethod() &&
4231 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4232 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004233 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004234 CreateBuiltins =
4235 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4236 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4237 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4238 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004239
4240 if (IsLinkageLookup)
4241 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004242
Richard Smithdd9459f2013-08-13 18:18:50 +00004243 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004244 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004245 LookupQualifiedName(Previous, DC);
4246
Douglas Gregor69605872012-03-28 16:01:27 +00004247 // C++ [dcl.meaning]p1:
4248 // When the declarator-id is qualified, the declaration shall refer to a
4249 // previously declared member of the class or namespace to which the
4250 // qualifier refers (or, in the case of a namespace, of an element of the
4251 // inline namespace set of that namespace (7.3.1)) or to a specialization
4252 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004253 //
Douglas Gregor69605872012-03-28 16:01:27 +00004254 // Note that we already checked the context above, and that we do not have
4255 // enough information to make sure that Previous contains the declaration
4256 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004257 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004258 // class X {
4259 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004260 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004261 // };
4262 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004263 // void X::f(int) { } // ill-formed
4264 //
Douglas Gregor69605872012-03-28 16:01:27 +00004265 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004266 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004267 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004268
4269 // C++ [dcl.meaning]p1:
4270 // [...] the member shall not merely have been introduced by a
4271 // using-declaration in the scope of the class or namespace nominated by
4272 // the nested-name-specifier of the declarator-id.
4273 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004274 }
4275
John McCall68263142009-11-18 22:49:29 +00004276 if (Previous.isSingleResult() &&
4277 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004278 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004279 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004280 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4281 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Douglas Gregor72c3f312008-12-05 18:15:24 +00004283 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004284 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004285 }
4286
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004287 // In C++, the previous declaration we find might be a tag type
4288 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004289 // tag type. Note that this does does not apply if we're declaring a
4290 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004291 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004292 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004293 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004294
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004295 // Check that there are no default arguments other than in the parameters
4296 // of a function declaration (C++ only).
4297 if (getLangOpts().CPlusPlus)
4298 CheckExtraCXXDefaultArguments(D);
4299
Nico Webere6bb76c2012-12-23 00:40:46 +00004300 NamedDecl *New;
4301
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004302 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004303 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004304 if (TemplateParamLists.size()) {
4305 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004306 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004307 }
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004309 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004310 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004311 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004312 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004313 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004314 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004315 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4316 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004317 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004318
4319 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004320 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004321
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004322 // If this has an identifier and is not an invalid redeclaration or
4323 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004324 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004325 !(D.isRedeclaration() && New->isInvalidDecl())) {
4326 // Only make a locally-scoped extern declaration visible if it is the first
4327 // declaration of this entity. Qualified lookup for such an entity should
4328 // only find this declaration if there is no visible declaration of it.
4329 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4330 PushOnScopeChains(New, S, AddToContext);
4331 if (!AddToContext)
4332 CurContext->addHiddenDecl(New);
4333 }
Mike Stump1eb44332009-09-09 15:08:12 +00004334
John McCalld226f652010-08-21 09:40:31 +00004335 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004336}
4337
Abramo Bagnara88adb982012-11-08 16:27:30 +00004338/// Helper method to turn variable array types into constant array
4339/// types in certain situations which would otherwise be errors (for
4340/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004341static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4342 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004343 bool &SizeIsNegative,
4344 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004345 // This method tries to turn a variable array into a constant
4346 // array even when the size isn't an ICE. This is necessary
4347 // for compatibility with code that depends on gcc's buggy
4348 // constant expression folding, like struct {char x[(int)(char*)2];}
4349 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004350 Oversized = 0;
4351
4352 if (T->isDependentType())
4353 return QualType();
4354
John McCall0953e762009-09-24 19:53:00 +00004355 QualifierCollector Qs;
4356 const Type *Ty = Qs.strip(T);
4357
4358 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004359 QualType Pointee = PTy->getPointeeType();
4360 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004361 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4362 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004363 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004364 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004365 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004366 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004367 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4368 QualType Inner = PTy->getInnerType();
4369 QualType FixedType =
4370 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4371 Oversized);
4372 if (FixedType.isNull()) return FixedType;
4373 FixedType = Context.getParenType(FixedType);
4374 return Qs.apply(Context, FixedType);
4375 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004376
4377 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004378 if (!VLATy)
4379 return QualType();
4380 // FIXME: We should probably handle this case
4381 if (VLATy->getElementType()->isVariablyModifiedType())
4382 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004383
Richard Smithaa9c3502011-12-07 00:43:50 +00004384 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004385 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004386 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004387 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004388
Douglas Gregor2767ce22010-08-18 00:39:00 +00004389 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004390 if (Res.isSigned() && Res.isNegative()) {
4391 SizeIsNegative = true;
4392 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004393 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004394
Douglas Gregor2767ce22010-08-18 00:39:00 +00004395 // Check whether the array is too large to be addressed.
4396 unsigned ActiveSizeBits
4397 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4398 Res);
4399 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4400 Oversized = Res;
4401 return QualType();
4402 }
4403
4404 return Context.getConstantArrayType(VLATy->getElementType(),
4405 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004406}
4407
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004408static void
4409FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004410 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4411 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4412 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4413 DstPTL.getPointeeLoc());
4414 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004415 return;
4416 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004417 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4418 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4419 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4420 DstPTL.getInnerLoc());
4421 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4422 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004423 return;
4424 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004425 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4426 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4427 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4428 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004429 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004430 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4431 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4432 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004433}
4434
Abramo Bagnara88adb982012-11-08 16:27:30 +00004435/// Helper method to turn variable array types into constant array
4436/// types in certain situations which would otherwise be errors (for
4437/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004438static TypeSourceInfo*
4439TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4440 ASTContext &Context,
4441 bool &SizeIsNegative,
4442 llvm::APSInt &Oversized) {
4443 QualType FixedTy
4444 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4445 SizeIsNegative, Oversized);
4446 if (FixedTy.isNull())
4447 return 0;
4448 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4449 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4450 FixedTInfo->getTypeLoc());
4451 return FixedTInfo;
4452}
4453
Richard Smith5ea6ef42013-01-10 23:43:47 +00004454/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004455/// that it can be found later for redeclarations. We include any extern "C"
4456/// declaration that is not visible in the translation unit here, not just
4457/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004458void
Richard Smith662f41b2013-06-18 20:15:12 +00004459Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004460 if (!getLangOpts().CPlusPlus &&
4461 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4462 // Don't need to track declarations in the TU in C.
4463 return;
4464
Douglas Gregor63935192009-03-02 00:19:53 +00004465 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004466 // FIXME: There can be multiple such declarations if they are functions marked
4467 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004468 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004469}
4470
Richard Smith662f41b2013-06-18 20:15:12 +00004471NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004472 if (ExternalSource) {
4473 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004474 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004475 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004476 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004477 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4478 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004479 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4480 if (Pos == LocallyScopedExternCDecls.end())
4481 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004482 }
4483 }
Richard Smith662f41b2013-06-18 20:15:12 +00004484
4485 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4486 return D ? cast<NamedDecl>(D->getMostRecentDecl()) : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004487}
4488
Eli Friedman85a53192009-04-07 19:37:57 +00004489/// \brief Diagnose function specifiers on a declaration of an identifier that
4490/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004491void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004492 // FIXME: We should probably indicate the identifier in question to avoid
4493 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004494 if (DS.isInlineSpecified())
4495 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004496 diag::err_inline_non_function);
4497
Richard Smithc7f81162013-03-18 22:52:47 +00004498 if (DS.isVirtualSpecified())
4499 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004500 diag::err_virtual_non_function);
4501
Richard Smithc7f81162013-03-18 22:52:47 +00004502 if (DS.isExplicitSpecified())
4503 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004504 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004505
Richard Smithc7f81162013-03-18 22:52:47 +00004506 if (DS.isNoreturnSpecified())
4507 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004508 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004509}
4510
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004511NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004512Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004513 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004514 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4515 if (D.getCXXScopeSpec().isSet()) {
4516 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4517 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004518 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004519 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004520 DC = CurContext;
4521 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004522 }
4523
Richard Smithc7f81162013-03-18 22:52:47 +00004524 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004525
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004526 if (D.getDeclSpec().isConstexprSpecified())
4527 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4528 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004529
Douglas Gregoraef01992010-07-13 06:37:01 +00004530 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4531 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4532 << D.getName().getSourceRange();
4533 return 0;
4534 }
4535
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004536 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004537 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004539 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004540 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004541
Richard Smith3e4c6c42011-05-05 21:57:07 +00004542 CheckTypedefForVariablyModifiedType(S, NewTD);
4543
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004544 bool Redeclaration = D.isRedeclaration();
4545 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4546 D.setRedeclaration(Redeclaration);
4547 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004548}
4549
Richard Smith3e4c6c42011-05-05 21:57:07 +00004550void
4551Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004552 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4553 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004554 // Note that variably modified types must be fixed before merging the decl so
4555 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004556 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4557 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004558 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004559 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004561 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004562 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004563 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004564 TypeSourceInfo *FixedTInfo =
4565 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4566 SizeIsNegative,
4567 Oversized);
4568 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004569 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004570 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004571 } else {
4572 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004573 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004574 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004575 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004576 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004577 Diag(NewTD->getLocation(), diag::err_array_too_large)
4578 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004579 else
Richard Smith162e1c12011-04-15 14:24:37 +00004580 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004581 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004582 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004583 }
4584 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004585}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004586
Richard Smith3e4c6c42011-05-05 21:57:07 +00004587
4588/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4589/// declares a typedef-name, either using the 'typedef' type specifier or via
4590/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4591NamedDecl*
4592Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4593 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004594 // Merge the decl with the existing one if appropriate. If the decl is
4595 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004596 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004597 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004598 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004599 if (!Previous.empty()) {
4600 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004601 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004602 }
4603
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004604 // If this is the C FILE type, notify the AST context.
4605 if (IdentifierInfo *II = NewTD->getIdentifier())
4606 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004607 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004608 if (II->isStr("FILE"))
4609 Context.setFILEDecl(NewTD);
4610 else if (II->isStr("jmp_buf"))
4611 Context.setjmp_bufDecl(NewTD);
4612 else if (II->isStr("sigjmp_buf"))
4613 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004614 else if (II->isStr("ucontext_t"))
4615 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004616 }
4617
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004618 return NewTD;
4619}
4620
Douglas Gregor8f301052009-02-24 19:23:27 +00004621/// \brief Determines whether the given declaration is an out-of-scope
4622/// previous declaration.
4623///
4624/// This routine should be invoked when name lookup has found a
4625/// previous declaration (PrevDecl) that is not in the scope where a
4626/// new declaration by the same name is being introduced. If the new
4627/// declaration occurs in a local scope, previous declarations with
4628/// linkage may still be considered previous declarations (C99
4629/// 6.2.2p4-5, C++ [basic.link]p6).
4630///
4631/// \param PrevDecl the previous declaration found by name
4632/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004633///
Douglas Gregor8f301052009-02-24 19:23:27 +00004634/// \param DC the context in which the new declaration is being
4635/// declared.
4636///
4637/// \returns true if PrevDecl is an out-of-scope previous declaration
4638/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004639static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004640isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4641 ASTContext &Context) {
4642 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004643 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004644
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004645 if (!PrevDecl->hasLinkage())
4646 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004647
David Blaikie4e4d0842012-03-11 07:00:24 +00004648 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004649 // C++ [basic.link]p6:
4650 // If there is a visible declaration of an entity with linkage
4651 // having the same name and type, ignoring entities declared
4652 // outside the innermost enclosing namespace scope, the block
4653 // scope declaration declares that same entity and receives the
4654 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004655 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004656 if (!OuterContext->isFunctionOrMethod())
4657 // This rule only applies to block-scope declarations.
4658 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004659
4660 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4661 if (PrevOuterContext->isRecord())
4662 // We found a member function: ignore it.
4663 return false;
4664
4665 // Find the innermost enclosing namespace for the new and
4666 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004667 OuterContext = OuterContext->getEnclosingNamespaceContext();
4668 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Douglas Gregor757c6002010-08-27 22:55:10 +00004670 // The previous declaration is in a different namespace, so it
4671 // isn't the same function.
4672 if (!OuterContext->Equals(PrevOuterContext))
4673 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004674 }
4675
Douglas Gregor8f301052009-02-24 19:23:27 +00004676 return true;
4677}
4678
John McCallb6217662010-03-15 10:12:16 +00004679static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4680 CXXScopeSpec &SS = D.getCXXScopeSpec();
4681 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004682 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004683}
4684
John McCallf85e1932011-06-15 23:02:42 +00004685bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4686 QualType type = decl->getType();
4687 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4688 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4689 // Various kinds of declaration aren't allowed to be __autoreleasing.
4690 unsigned kind = -1U;
4691 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4692 if (var->hasAttr<BlocksAttr>())
4693 kind = 0; // __block
4694 else if (!var->hasLocalStorage())
4695 kind = 1; // global
4696 } else if (isa<ObjCIvarDecl>(decl)) {
4697 kind = 3; // ivar
4698 } else if (isa<FieldDecl>(decl)) {
4699 kind = 2; // field
4700 }
4701
4702 if (kind != -1U) {
4703 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4704 << kind;
4705 }
4706 } else if (lifetime == Qualifiers::OCL_None) {
4707 // Try to infer lifetime.
4708 if (!type->isObjCLifetimeType())
4709 return false;
4710
4711 lifetime = type->getObjCARCImplicitLifetime();
4712 type = Context.getLifetimeQualifiedType(type, lifetime);
4713 decl->setType(type);
4714 }
4715
4716 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4717 // Thread-local variables cannot have lifetime.
4718 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004719 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004720 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004721 << var->getType();
4722 return true;
4723 }
4724 }
4725
4726 return false;
4727}
4728
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004729static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4730 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004731 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004732 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004733 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4734 ND.dropAttr<WeakAttr>();
4735 }
4736 }
4737 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004738 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004739 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4740 ND.dropAttr<WeakRefAttr>();
4741 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004742 }
Reid Klecknera7225342013-05-20 14:02:37 +00004743
4744 // 'selectany' only applies to externally visible varable declarations.
4745 // It does not apply to functions.
4746 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4747 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4748 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4749 ND.dropAttr<SelectAnyAttr>();
4750 }
4751 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004752}
4753
John McCallb421d922013-04-02 02:48:58 +00004754/// Given that we are within the definition of the given function,
4755/// will that definition behave like C99's 'inline', where the
4756/// definition is discarded except for optimization purposes?
4757static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4758 // Try to avoid calling GetGVALinkageForFunction.
4759
4760 // All cases of this require the 'inline' keyword.
4761 if (!FD->isInlined()) return false;
4762
4763 // This is only possible in C++ with the gnu_inline attribute.
4764 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4765 return false;
4766
4767 // Okay, go ahead and call the relatively-more-expensive function.
4768
4769#ifndef NDEBUG
4770 // AST quite reasonably asserts that it's working on a function
4771 // definition. We don't really have a way to tell it that we're
4772 // currently defining the function, so just lie to it in +Asserts
4773 // builds. This is an awful hack.
4774 FD->setLazyBody(1);
4775#endif
4776
4777 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4778
4779#ifndef NDEBUG
4780 FD->setLazyBody(0);
4781#endif
4782
4783 return isC99Inline;
4784}
4785
Richard Smithaa4bc182013-06-30 09:48:50 +00004786/// Determine whether a variable is extern "C" prior to attaching
4787/// an initializer. We can't just call isExternC() here, because that
4788/// will also compute and cache whether the declaration is externally
4789/// visible, which might change when we attach the initializer.
4790///
4791/// This can only be used if the declaration is known to not be a
4792/// redeclaration of an internal linkage declaration.
4793///
4794/// For instance:
4795///
4796/// auto x = []{};
4797///
4798/// Attaching the initializer here makes this declaration not externally
4799/// visible, because its type has internal linkage.
4800///
4801/// FIXME: This is a hack.
4802template<typename T>
4803static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4804 if (S.getLangOpts().CPlusPlus) {
4805 // In C++, the overloadable attribute negates the effects of extern "C".
4806 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4807 return false;
4808 }
4809 return D->isExternC();
4810}
4811
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004812static bool shouldConsiderLinkage(const VarDecl *VD) {
4813 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4814 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004815 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004816 if (DC->isFileContext())
4817 return true;
4818 if (DC->isRecord())
4819 return false;
4820 llvm_unreachable("Unexpected context");
4821}
4822
4823static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4824 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4825 if (DC->isFileContext() || DC->isFunctionOrMethod())
4826 return true;
4827 if (DC->isRecord())
4828 return false;
4829 llvm_unreachable("Unexpected context");
4830}
4831
Richard Smitha41c97a2013-09-20 01:15:31 +00004832/// Adjust the \c DeclContext for a function or variable that might be a
4833/// function-local external declaration.
4834bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4835 if (!DC->isFunctionOrMethod())
4836 return false;
4837
4838 // If this is a local extern function or variable declared within a function
4839 // template, don't add it into the enclosing namespace scope until it is
4840 // instantiated; it might have a dependent type right now.
4841 if (DC->isDependentContext())
4842 return true;
4843
4844 // C++11 [basic.link]p7:
4845 // When a block scope declaration of an entity with linkage is not found to
4846 // refer to some other declaration, then that entity is a member of the
4847 // innermost enclosing namespace.
4848 //
4849 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4850 // semantically-enclosing namespace, not a lexically-enclosing one.
4851 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4852 DC = DC->getParent();
4853 return true;
4854}
4855
Larisse Voufoef4579c2013-08-06 01:03:05 +00004856NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004857Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004858 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004859 MultiTemplateParamsArg TemplateParamLists,
4860 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004861 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004862 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004863
Douglas Gregor16573fa2010-04-19 22:54:31 +00004864 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004865 VarDecl::StorageClass SC =
4866 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004867
Richard Smitha41c97a2013-09-20 01:15:31 +00004868 DeclContext *OriginalDC = DC;
4869 bool IsLocalExternDecl = SC == SC_Extern &&
4870 adjustContextForLocalExternDecl(DC);
4871
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004872 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004873 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4874 // half array type (unless the cl_khr_fp16 extension is enabled).
4875 if (Context.getBaseElementType(R)->isHalfType()) {
4876 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4877 D.setInvalidType();
4878 }
4879 }
4880
Douglas Gregor16573fa2010-04-19 22:54:31 +00004881 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004882 // mutable can only appear on non-static class members, so it's always
4883 // an error here
4884 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004885 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004886 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004887 }
John McCallb421d922013-04-02 02:48:58 +00004888
Richard Smith9109bf12013-06-17 01:34:01 +00004889 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4890 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4891 D.getDeclSpec().getStorageClassSpecLoc())) {
4892 // In C++11, the 'register' storage class specifier is deprecated.
4893 // Suppress the warning in system macros, it's used in macros in some
4894 // popular C system headers, such as in glibc's htonl() macro.
4895 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4896 diag::warn_deprecated_register)
4897 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4898 }
4899
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004900 IdentifierInfo *II = Name.getAsIdentifierInfo();
4901 if (!II) {
4902 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004903 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004904 return 0;
4905 }
4906
Richard Smithc7f81162013-03-18 22:52:47 +00004907 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004908
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004909 if (!DC->isRecord() && S->getFnParent() == 0) {
4910 // C99 6.9p2: The storage-class specifiers auto and register shall not
4911 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00004912 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004913 // If this is a register variable with an asm label specified, then this
4914 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00004915 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004916 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4917 else
4918 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004919 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004920 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004921 }
Richard Smith9109bf12013-06-17 01:34:01 +00004922
David Blaikie4e4d0842012-03-11 07:00:24 +00004923 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004924 // Set up the special work-group-local storage class for variables in the
4925 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00004926 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004927 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00004928 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00004929
Guy Benyei21f18c42013-02-07 10:55:47 +00004930 // OpenCL v1.2 s6.9.b p4:
4931 // The sampler type cannot be used with the __local and __global address
4932 // space qualifiers.
4933 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
4934 R.getAddressSpace() == LangAS::opencl_global)) {
4935 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
4936 }
4937
Guy Benyeie6b9d802013-01-20 12:31:11 +00004938 // OpenCL 1.2 spec, p6.9 r:
4939 // The event type cannot be used to declare a program scope variable.
4940 // The event type cannot be used with the __local, __constant and __global
4941 // address space qualifiers.
4942 if (R->isEventT()) {
4943 if (S->getParent() == 0) {
4944 Diag(D.getLocStart(), diag::err_event_t_global_var);
4945 D.setInvalidType();
4946 }
4947
4948 if (R.getAddressSpace()) {
4949 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
4950 D.setInvalidType();
4951 }
4952 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004953 }
4954
Larisse Voufoef4579c2013-08-06 01:03:05 +00004955 bool IsExplicitSpecialization = false;
4956 bool IsVariableTemplateSpecialization = false;
4957 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00004958 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004959 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00004960 VarDecl *NewVD = 0;
4961 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00004962 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004963 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004964 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004965 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004966
4967 if (D.isInvalidType())
4968 NewVD->setInvalidDecl();
4969 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00004970 bool Invalid = false;
4971
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004972 if (DC->isRecord() && !CurContext->isRecord()) {
4973 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00004974 switch (SC) {
4975 case SC_None:
4976 break;
4977 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004978 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4979 diag::err_static_out_of_line)
4980 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00004981 break;
4982 case SC_Auto:
4983 case SC_Register:
4984 case SC_Extern:
4985 // [dcl.stc] p2: The auto or register specifiers shall be applied only
4986 // to names of variables declared in a block or to function parameters.
4987 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
4988 // of class members
4989
4990 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4991 diag::err_storage_class_for_static_member)
4992 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4993 break;
4994 case SC_PrivateExtern:
4995 llvm_unreachable("C storage class in c++!");
4996 case SC_OpenCLWorkGroupLocal:
4997 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00004998 }
Larisse Voufo06935f32013-08-06 03:43:07 +00004999 }
5000
Richard Smithb9c64d82012-02-16 20:41:22 +00005001 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005002 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5003 if (RD->isLocalClass())
5004 Diag(D.getIdentifierLoc(),
5005 diag::err_static_data_member_not_allowed_in_local_class)
5006 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005007
Richard Smithb9c64d82012-02-16 20:41:22 +00005008 // C++98 [class.union]p1: If a union contains a static data member,
5009 // the program is ill-formed. C++11 drops this restriction.
5010 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005011 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005012 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005013 ? diag::warn_cxx98_compat_static_data_member_in_union
5014 : diag::ext_static_data_member_in_union) << Name;
5015 // We conservatively disallow static data members in anonymous structs.
5016 else if (!RD->getDeclName())
5017 Diag(D.getIdentifierLoc(),
5018 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005019 << Name << RD->isUnion();
5020 }
5021 }
5022
Larisse Voufoef4579c2013-08-06 01:03:05 +00005023 NamedDecl *PrevDecl = 0;
5024 if (Previous.begin() != Previous.end())
5025 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5026 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5027
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005028 // Match up the template parameter lists with the scope specifier, then
5029 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005030 TemplateParameterList *TemplateParams =
5031 MatchTemplateParametersToScopeSpecifier(
5032 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5033 D.getCXXScopeSpec(), TemplateParamLists,
5034 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005035 if (TemplateParams) {
5036 if (!TemplateParams->size() &&
5037 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005038 // There is an extraneous 'template<>' for this variable. Complain
5039 // about it, but allow the declaration of the variable.
5040 Diag(TemplateParams->getTemplateLoc(),
5041 diag::err_template_variable_noparams)
5042 << II
5043 << SourceRange(TemplateParams->getTemplateLoc(),
5044 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005045 } else {
5046 // Only C++1y supports variable templates (N3651).
5047 Diag(D.getIdentifierLoc(),
5048 getLangOpts().CPlusPlus1y
5049 ? diag::warn_cxx11_compat_variable_template
5050 : diag::ext_variable_template);
5051
5052 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5053 // This is an explicit specialization or a partial specialization.
5054 // Check that we can declare a specialization here
5055
5056 IsVariableTemplateSpecialization = true;
5057 IsPartialSpecialization = TemplateParams->size() > 0;
5058
5059 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005060 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005061 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005062
5063 // Check that we can declare a template here.
5064 if (CheckTemplateDeclScope(S, TemplateParams))
5065 return 0;
5066
5067 // If there is a previous declaration with the same name, check
5068 // whether this is a valid redeclaration.
5069 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5070 PrevDecl = PrevVarTemplate = 0;
5071
5072 if (PrevVarTemplate) {
5073 // Ensure that the template parameter lists are compatible.
5074 if (!TemplateParameterListsAreEqual(
5075 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5076 /*Complain=*/true, TPL_TemplateMatch))
5077 return 0;
5078 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5079 // Maybe we will complain about the shadowed template parameter.
5080 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5081
5082 // Just pretend that we didn't see the previous declaration.
5083 PrevDecl = 0;
5084 } else if (PrevDecl) {
5085 // C++ [temp]p5:
5086 // ... a template name declared in namespace scope or in class
5087 // scope shall be unique in that scope.
5088 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5089 << Name;
5090 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5091 return 0;
5092 }
5093
5094 // Check the template parameter list of this declaration, possibly
5095 // merging in the template parameter list from the previous variable
5096 // template declaration.
5097 if (CheckTemplateParameterList(
5098 TemplateParams,
5099 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5100 : 0,
5101 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5102 DC->isDependentContext())
5103 ? TPC_ClassTemplateMember
5104 : TPC_VarTemplate))
5105 Invalid = true;
5106
5107 if (D.getCXXScopeSpec().isSet()) {
5108 // If the name of the template was qualified, we must be defining
5109 // the template out-of-line.
5110 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5111 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005112 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5113 << Name << DC << /*IsDefinition*/true
5114 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005115 Invalid = true;
5116 }
5117 }
5118 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005119 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005120 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5121 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5122
5123 // We have encountered something that the user meant to be a
5124 // specialization (because it has explicitly-specified template
5125 // arguments) but that was not introduced with a "template<>" (or had
5126 // too few of them).
5127 // FIXME: Differentiate between attempts for explicit instantiations
5128 // (starting with "template") and the rest.
5129 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5130 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5131 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5132 "template<> ");
5133 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005134 }
Mike Stump1eb44332009-09-09 15:08:12 +00005135
Larisse Voufoef4579c2013-08-06 01:03:05 +00005136 if (IsVariableTemplateSpecialization) {
5137 if (!PrevVarTemplate) {
5138 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5139 << IsPartialSpecialization;
5140 return 0;
5141 }
5142
5143 SourceLocation TemplateKWLoc =
5144 TemplateParamLists.size() > 0
5145 ? TemplateParamLists[0]->getTemplateLoc()
5146 : SourceLocation();
5147 DeclResult Res = ActOnVarTemplateSpecialization(
5148 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5149 IsPartialSpecialization);
5150 if (Res.isInvalid())
5151 return 0;
5152 NewVD = cast<VarDecl>(Res.get());
5153 AddToScope = false;
5154 } else
5155 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5156 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005157
Larisse Voufo567f9172013-08-22 00:59:14 +00005158 // If this is supposed to be a variable template, create it as such.
5159 if (IsVariableTemplate) {
5160 NewTemplate =
5161 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5162 TemplateParams, NewVD, PrevVarTemplate);
5163 NewVD->setDescribedVarTemplate(NewTemplate);
5164 }
5165
Richard Smith483b9f32011-02-21 20:05:19 +00005166 // If this decl has an auto type in need of deduction, make a note of the
5167 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005168 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005169 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005170
Larisse Voufo567f9172013-08-22 00:59:14 +00005171 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005172 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005173 if (NewTemplate)
5174 NewTemplate->setInvalidDecl();
5175 }
Mike Stump1eb44332009-09-09 15:08:12 +00005176
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005177 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005178
Larisse Voufoef4579c2013-08-06 01:03:05 +00005179 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5180 if (TemplateParams && TemplateParamLists.size() > 1 &&
5181 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5182 NewVD->setTemplateParameterListsInfo(
5183 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5184 } else if (IsVariableTemplateSpecialization ||
5185 (!TemplateParams && TemplateParamLists.size() > 0 &&
5186 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005187 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005188 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005189 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005190 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005191
Richard Smith7ca48502012-02-13 22:16:19 +00005192 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005193 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005194 }
5195
Douglas Gregore3895852011-09-12 18:37:38 +00005196 // Set the lexical context. If the declarator has a C++ scope specifier, the
5197 // lexical context will be different from the semantic context.
5198 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005199 if (NewTemplate)
5200 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005201
Richard Smitha41c97a2013-09-20 01:15:31 +00005202 if (IsLocalExternDecl)
5203 NewVD->setLocalExternDecl();
5204
Richard Smithec642442013-04-12 22:46:28 +00005205 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005206 if (NewVD->hasLocalStorage()) {
5207 // C++11 [dcl.stc]p4:
5208 // When thread_local is applied to a variable of block scope the
5209 // storage-class-specifier static is implied if it does not appear
5210 // explicitly.
5211 // Core issue: 'static' is not implied if the variable is declared
5212 // 'extern'.
5213 if (SCSpec == DeclSpec::SCS_unspecified &&
5214 TSCS == DeclSpec::TSCS_thread_local &&
5215 DC->isFunctionOrMethod())
5216 NewVD->setTSCSpec(TSCS);
5217 else
5218 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5219 diag::err_thread_non_global)
5220 << DeclSpec::getSpecifierName(TSCS);
5221 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005222 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5223 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005224 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005225 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005226 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005227
John McCallb421d922013-04-02 02:48:58 +00005228 // C99 6.7.4p3
5229 // An inline definition of a function with external linkage shall
5230 // not contain a definition of a modifiable object with static or
5231 // thread storage duration...
5232 // We only apply this when the function is required to be defined
5233 // elsewhere, i.e. when the function is not 'extern inline'. Note
5234 // that a local variable with thread storage duration still has to
5235 // be marked 'static'. Also note that it's possible to get these
5236 // semantics in C++ using __attribute__((gnu_inline)).
5237 if (SC == SC_Static && S->getFnParent() != 0 &&
5238 !NewVD->getType().isConstQualified()) {
5239 FunctionDecl *CurFD = getCurFunctionDecl();
5240 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5241 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5242 diag::warn_static_local_in_extern_inline);
5243 MaybeSuggestAddingStaticToDecl(CurFD);
5244 }
5245 }
5246
Douglas Gregord023aec2011-09-09 20:53:38 +00005247 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005248 if (IsVariableTemplateSpecialization)
5249 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5250 << (IsPartialSpecialization ? 1 : 0)
5251 << FixItHint::CreateRemoval(
5252 D.getDeclSpec().getModulePrivateSpecLoc());
5253 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005254 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5255 << 2
5256 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005257 else if (NewVD->hasLocalStorage())
5258 Diag(NewVD->getLocation(), diag::err_module_private_local)
5259 << 0 << NewVD->getDeclName()
5260 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5261 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005262 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005263 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005264 if (NewTemplate)
5265 NewTemplate->setModulePrivate();
5266 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005267 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005268
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005269 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005270 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005271
Richard Smithbe507b62013-02-01 08:12:08 +00005272 if (NewVD->hasAttrs())
5273 CheckAlignasUnderalignment(NewVD);
5274
Peter Collingbournec0c00662012-08-28 20:37:50 +00005275 if (getLangOpts().CUDA) {
5276 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5277 // storage [duration]."
5278 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005279 (NewVD->hasAttr<CUDASharedAttr>() ||
5280 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005281 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005282 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005283 }
5284
John McCallf85e1932011-06-15 23:02:42 +00005285 // In auto-retain/release, infer strong retension for variables of
5286 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005287 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005288 NewVD->setInvalidDecl();
5289
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005290 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005291 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005292 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005293 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005294 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005295 if (S->getFnParent() != 0) {
5296 switch (SC) {
5297 case SC_None:
5298 case SC_Auto:
5299 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5300 break;
5301 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005302 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005303 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5304 break;
5305 case SC_Static:
5306 case SC_Extern:
5307 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005308 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005309 break;
5310 }
5311 }
5312
5313 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005314 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005315 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5316 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5317 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5318 if (I != ExtnameUndeclaredIdentifiers.end()) {
5319 NewVD->addAttr(I->second);
5320 ExtnameUndeclaredIdentifiers.erase(I);
5321 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005322 }
5323
John McCall8472af42010-03-16 21:48:18 +00005324 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005325 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005326 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005327
John McCall68263142009-11-18 22:49:29 +00005328 // Don't consider existing declarations that are in a different
5329 // scope and are out-of-semantic-context declarations (if the new
5330 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005331 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005332 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005333 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5334
Richard Smithdd9459f2013-08-13 18:18:50 +00005335 // Check whether the previous declaration is in the same block scope. This
5336 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5337 if (getLangOpts().CPlusPlus &&
5338 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5339 NewVD->setPreviousDeclInSameBlockScope(
5340 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005341 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005342
David Blaikie4e4d0842012-03-11 07:00:24 +00005343 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005344 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5345 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005346 // Merge the decl with the existing one if appropriate.
5347 if (!Previous.empty()) {
5348 if (Previous.isSingleResult() &&
5349 isa<FieldDecl>(Previous.getFoundDecl()) &&
5350 D.getCXXScopeSpec().isSet()) {
5351 // The user tried to define a non-static data member
5352 // out-of-line (C++ [dcl.meaning]p1).
5353 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5354 << D.getCXXScopeSpec().getRange();
5355 Previous.clear();
5356 NewVD->setInvalidDecl();
5357 }
5358 } else if (D.getCXXScopeSpec().isSet()) {
5359 // No previous declaration in the qualifying scope.
5360 Diag(D.getIdentifierLoc(), diag::err_no_member)
5361 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005362 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005363 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005364 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005365
Larisse Voufoef4579c2013-08-06 01:03:05 +00005366 if (!IsVariableTemplateSpecialization) {
5367 if (PrevVarTemplate) {
5368 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5369 LookupOrdinaryName, ForRedeclaration);
5370 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005371 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005372 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005373 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005374 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005375
5376 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005377 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005378 CheckMemberSpecialization(NewVD, Previous))
5379 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005380 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005381
Rafael Espindola65611bf2013-03-02 21:41:48 +00005382 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005383 checkAttributesAfterMerging(*this, *NewVD);
5384
Richard Smithaa4bc182013-06-30 09:48:50 +00005385 // If this is the first declaration of an extern C variable, update
5386 // the map of such variables.
5387 if (!NewVD->getPreviousDecl() && !NewVD->isInvalidDecl() &&
5388 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005389 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005390
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005391 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005392 Decl *ManglingContextDecl;
5393 if (MangleNumberingContext *MCtx =
5394 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5395 ManglingContextDecl)) {
5396 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5397 }
5398 }
5399
Larisse Voufoef4579c2013-08-06 01:03:05 +00005400 // If we are providing an explicit specialization of a static variable
5401 // template, make a note of that.
5402 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005403 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005404
Larisse Voufo567f9172013-08-22 00:59:14 +00005405 if (NewTemplate) {
5406 ActOnDocumentableDecl(NewTemplate);
5407 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005408 }
5409
Larisse Voufo567f9172013-08-22 00:59:14 +00005410 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005411}
5412
John McCall053f4bd2010-03-22 09:20:08 +00005413/// \brief Diagnose variable or built-in function shadowing. Implements
5414/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005415///
John McCall053f4bd2010-03-22 09:20:08 +00005416/// This method is called whenever a VarDecl is added to a "useful"
5417/// scope.
John McCall8472af42010-03-16 21:48:18 +00005418///
John McCalla369a952010-03-20 04:12:52 +00005419/// \param S the scope in which the shadowing name is being declared
5420/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005421///
John McCall053f4bd2010-03-22 09:20:08 +00005422void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005423 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005424 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005425 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005426 return;
5427
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005428 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005429 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005430 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005431
5432 DeclContext *NewDC = D->getDeclContext();
5433
John McCalla369a952010-03-20 04:12:52 +00005434 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005435 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005436 return;
John McCall8472af42010-03-16 21:48:18 +00005437
John McCall8472af42010-03-16 21:48:18 +00005438 NamedDecl* ShadowedDecl = R.getFoundDecl();
5439 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5440 return;
5441
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005442 // Fields are not shadowed by variables in C++ static methods.
5443 if (isa<FieldDecl>(ShadowedDecl))
5444 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5445 if (MD->isStatic())
5446 return;
5447
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005448 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5449 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005450 // For shadowing external vars, make sure that we point to the global
5451 // declaration, not a locally scoped extern declaration.
5452 for (VarDecl::redecl_iterator
5453 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5454 I != E; ++I)
5455 if (I->isFileVarDecl()) {
5456 ShadowedDecl = *I;
5457 break;
5458 }
5459 }
5460
5461 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5462
John McCalla369a952010-03-20 04:12:52 +00005463 // Only warn about certain kinds of shadowing for class members.
5464 if (NewDC && NewDC->isRecord()) {
5465 // In particular, don't warn about shadowing non-class members.
5466 if (!OldDC->isRecord())
5467 return;
5468
5469 // TODO: should we warn about static data members shadowing
5470 // static data members from base classes?
5471
5472 // TODO: don't diagnose for inaccessible shadowed members.
5473 // This is hard to do perfectly because we might friend the
5474 // shadowing context, but that's just a false negative.
5475 }
5476
5477 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005478 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005479 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005480 if (isa<FieldDecl>(ShadowedDecl))
5481 Kind = 3; // field
5482 else
5483 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005484 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005485 Kind = 1; // global
5486 else
5487 Kind = 0; // local
5488
John McCalla369a952010-03-20 04:12:52 +00005489 DeclarationName Name = R.getLookupName();
5490
John McCall8472af42010-03-16 21:48:18 +00005491 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005492 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005493 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5494}
5495
John McCall053f4bd2010-03-22 09:20:08 +00005496/// \brief Check -Wshadow without the advantage of a previous lookup.
5497void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005498 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005499 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005500 return;
5501
John McCall053f4bd2010-03-22 09:20:08 +00005502 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5503 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5504 LookupName(R, S);
5505 CheckShadow(S, D, R);
5506}
5507
Richard Smithaa4bc182013-06-30 09:48:50 +00005508/// Check for conflict between this global or extern "C" declaration and
5509/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005510template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005511static bool checkGlobalOrExternCConflict(
5512 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5513 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5514 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005515
Richard Smithaa4bc182013-06-30 09:48:50 +00005516 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5517 // The common case: this global doesn't conflict with any extern "C"
5518 // declaration.
5519 return false;
5520 }
5521
5522 if (Prev) {
5523 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5524 // Both the old and new declarations have C language linkage. This is a
5525 // redeclaration.
5526 Previous.clear();
5527 Previous.addDecl(Prev);
5528 return true;
5529 }
5530
5531 // This is a global, non-extern "C" declaration, and there is a previous
5532 // non-global extern "C" declaration. Diagnose if this is a variable
5533 // declaration.
5534 if (!isa<VarDecl>(ND))
5535 return false;
5536 } else {
5537 // The declaration is extern "C". Check for any declaration in the
5538 // translation unit which might conflict.
5539 if (IsGlobal) {
5540 // We have already performed the lookup into the translation unit.
5541 IsGlobal = false;
5542 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5543 I != E; ++I) {
5544 if (isa<VarDecl>(*I)) {
5545 Prev = *I;
5546 break;
5547 }
5548 }
5549 } else {
5550 DeclContext::lookup_result R =
5551 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5552 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5553 I != E; ++I) {
5554 if (isa<VarDecl>(*I)) {
5555 Prev = *I;
5556 break;
5557 }
5558 // FIXME: If we have any other entity with this name in global scope,
5559 // the declaration is ill-formed, but that is a defect: it breaks the
5560 // 'stat' hack, for instance. Only variables can have mangled name
5561 // clashes with extern "C" declarations, so only they deserve a
5562 // diagnostic.
5563 }
5564 }
5565
5566 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005567 return false;
5568 }
5569
Richard Smithaa4bc182013-06-30 09:48:50 +00005570 // Use the first declaration's location to ensure we point at something which
5571 // is lexically inside an extern "C" linkage-spec.
5572 assert(Prev && "should have found a previous declaration to diagnose");
5573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5574 Prev = FD->getFirstDeclaration();
5575 else
5576 Prev = cast<VarDecl>(Prev)->getFirstDeclaration();
5577
5578 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5579 << IsGlobal << ND;
5580 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5581 << IsGlobal;
5582 return false;
5583}
5584
5585/// Apply special rules for handling extern "C" declarations. Returns \c true
5586/// if we have found that this is a redeclaration of some prior entity.
5587///
5588/// Per C++ [dcl.link]p6:
5589/// Two declarations [for a function or variable] with C language linkage
5590/// with the same name that appear in different scopes refer to the same
5591/// [entity]. An entity with C language linkage shall not be declared with
5592/// the same name as an entity in global scope.
5593template<typename T>
5594static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5595 LookupResult &Previous) {
5596 if (!S.getLangOpts().CPlusPlus) {
5597 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005598 // variable declared in function scope. We don't need this in C++, because
5599 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005600 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5601 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5602 Previous.clear();
5603 Previous.addDecl(Prev);
5604 return true;
5605 }
5606 }
5607 return false;
5608 }
5609
5610 // A declaration in the translation unit can conflict with an extern "C"
5611 // declaration.
5612 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5613 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5614
5615 // An extern "C" declaration can conflict with a declaration in the
5616 // translation unit or can be a redeclaration of an extern "C" declaration
5617 // in another scope.
5618 if (isIncompleteDeclExternC(S,ND))
5619 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5620
5621 // Neither global nor extern "C": nothing to do.
5622 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005623}
5624
Richard Smithdc7a4f52013-04-30 13:56:41 +00005625void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005626 // If the decl is already known invalid, don't check it.
5627 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005628 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005630 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5631 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005632
Richard Smithdc7a4f52013-04-30 13:56:41 +00005633 // Defer checking an 'auto' type until its initializer is attached.
5634 if (T->isUndeducedType())
5635 return;
5636
John McCallc12c5bb2010-05-15 11:32:37 +00005637 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005638 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5639 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005640 T = Context.getObjCObjectPointerType(T);
5641 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005642 }
Mike Stump1eb44332009-09-09 15:08:12 +00005643
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005644 // Emit an error if an address space was applied to decl with local storage.
5645 // This includes arrays of objects with address space qualifiers, but not
5646 // automatic variables that point to other address spaces.
5647 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005648 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005649 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005650 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005651 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005652 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005653
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005654 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5655 // __constant address space.
5656 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5657 && T.getAddressSpace() != LangAS::opencl_constant
5658 && !T->isSamplerT()){
5659 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5660 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005661 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005662 }
5663
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005664 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5665 // scope.
5666 if ((getLangOpts().OpenCLVersion >= 120)
5667 && NewVD->isStaticLocal()) {
5668 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5669 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005670 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005671 }
5672
Mike Stumpf33651c2009-04-14 00:57:29 +00005673 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005674 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005675 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005676 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005677 else {
5678 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005679 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005680 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005681 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005682
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005683 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005684 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005685 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005686 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005687
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005688 if ((isVM && NewVD->hasLinkage()) ||
5689 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005690 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005691 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005692 TypeSourceInfo *FixedTInfo =
5693 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5694 SizeIsNegative, Oversized);
5695 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005696 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005697 // FIXME: This won't give the correct result for
5698 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005699 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005700
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005701 if (NewVD->isFileVarDecl())
5702 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005703 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005704 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005705 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005706 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005707 else
5708 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005709 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005710 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005711 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005712 }
5713
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005714 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005715 if (NewVD->isFileVarDecl())
5716 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5717 else
5718 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005719 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005720 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005721 }
Mike Stump1eb44332009-09-09 15:08:12 +00005722
Chris Lattnereaaebc72009-04-25 08:06:05 +00005723 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005724 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005725 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005726 }
5727
David Majnemeraa715672013-05-29 00:56:45 +00005728 if (T->isVoidType()) {
5729 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5730 // of objects and functions.
5731 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5732 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5733 << T;
5734 NewVD->setInvalidDecl();
5735 return;
5736 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005737 }
5738
5739 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5740 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5741 NewVD->setInvalidDecl();
5742 return;
5743 }
5744
5745 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5746 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5747 NewVD->setInvalidDecl();
5748 return;
5749 }
5750
5751 if (NewVD->isConstexpr() && !T->isDependentType() &&
5752 RequireLiteralType(NewVD->getLocation(), T,
5753 diag::err_constexpr_var_non_literal)) {
5754 // Can't perform this check until the type is deduced.
5755 NewVD->setInvalidDecl();
5756 return;
5757 }
5758}
5759
5760/// \brief Perform semantic checking on a newly-created variable
5761/// declaration.
5762///
5763/// This routine performs all of the type-checking required for a
5764/// variable declaration once it has been built. It is used both to
5765/// check variables after they have been parsed and their declarators
5766/// have been translated into a declaration, and to check variables
5767/// that have been instantiated from a template.
5768///
5769/// Sets NewVD->isInvalidDecl() if an error was encountered.
5770///
5771/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005772bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005773 CheckVariableDeclarationType(NewVD);
5774
5775 // If the decl is already known invalid, don't check it.
5776 if (NewVD->isInvalidDecl())
5777 return false;
5778
John McCall5b8740f2013-04-01 18:34:28 +00005779 // If we did not find anything by this name, look for a non-visible
5780 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005781 if (Previous.empty() &&
5782 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005783 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005784
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005785 // Filter out any non-conflicting previous declarations.
5786 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5787
John McCall68263142009-11-18 22:49:29 +00005788 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005789 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005790 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005791 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005792 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005793}
5794
Douglas Gregora8f32e02009-10-06 17:59:45 +00005795/// \brief Data used with FindOverriddenMethod
5796struct FindOverriddenMethodData {
5797 Sema *S;
5798 CXXMethodDecl *Method;
5799};
5800
5801/// \brief Member lookup function that determines whether a given C++
5802/// method overrides a method in a base class, to be used with
5803/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005804static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005805 CXXBasePath &Path,
5806 void *UserData) {
5807 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005808
Douglas Gregora8f32e02009-10-06 17:59:45 +00005809 FindOverriddenMethodData *Data
5810 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005811
5812 DeclarationName Name = Data->Method->getDeclName();
5813
5814 // FIXME: Do we care about other names here too?
5815 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005816 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005817 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5818 CanQualType CT = Data->S->Context.getCanonicalType(T);
5819
Anders Carlsson1a689722009-11-27 01:26:58 +00005820 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005821 }
5822
5823 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005824 !Path.Decls.empty();
5825 Path.Decls = Path.Decls.slice(1)) {
5826 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005827 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5828 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005829 return true;
5830 }
5831 }
5832
5833 return false;
5834}
5835
David Blaikie5708c182012-10-17 00:47:58 +00005836namespace {
5837 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5838}
5839/// \brief Report an error regarding overriding, along with any relevant
5840/// overriden methods.
5841///
5842/// \param DiagID the primary error to report.
5843/// \param MD the overriding method.
5844/// \param OEK which overrides to include as notes.
5845static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5846 OverrideErrorKind OEK = OEK_All) {
5847 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5848 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5849 E = MD->end_overridden_methods();
5850 I != E; ++I) {
5851 // This check (& the OEK parameter) could be replaced by a predicate, but
5852 // without lambdas that would be overkill. This is still nicer than writing
5853 // out the diag loop 3 times.
5854 if ((OEK == OEK_All) ||
5855 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5856 (OEK == OEK_Deleted && (*I)->isDeleted()))
5857 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5858 }
5859}
5860
Sebastian Redla165da02009-11-18 21:51:29 +00005861/// AddOverriddenMethods - See if a method overrides any in the base classes,
5862/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005863bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005864 // Look for virtual methods in base classes that this method might override.
5865 CXXBasePaths Paths;
5866 FindOverriddenMethodData Data;
5867 Data.Method = MD;
5868 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005869 bool hasDeletedOverridenMethods = false;
5870 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005871 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005872 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5873 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5874 E = Paths.found_decls_end(); I != E; ++I) {
5875 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005876 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005877 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005878 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005879 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005880 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005881 hasDeletedOverridenMethods |= OldMD->isDeleted();
5882 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005883 AddedAny = true;
5884 }
Sebastian Redla165da02009-11-18 21:51:29 +00005885 }
5886 }
5887 }
David Blaikie5708c182012-10-17 00:47:58 +00005888
5889 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5890 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5891 }
5892 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5893 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5894 }
5895
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005896 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005897}
5898
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005899namespace {
5900 // Struct for holding all of the extra arguments needed by
5901 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5902 struct ActOnFDArgs {
5903 Scope *S;
5904 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005905 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005906 bool AddToScope;
5907 };
5908}
5909
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005910namespace {
5911
5912// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005913// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005914class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5915 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005916 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5917 CXXRecordDecl *Parent)
5918 : Context(Context), OriginalFD(TypoFD),
5919 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005920
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005921 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005922 if (candidate.getEditDistance() == 0)
5923 return false;
5924
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005925 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005926 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5927 CDeclEnd = candidate.end();
5928 CDecl != CDeclEnd; ++CDecl) {
5929 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5930
5931 if (FD && !FD->hasBody() &&
5932 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5933 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5934 CXXRecordDecl *Parent = MD->getParent();
5935 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5936 return true;
5937 } else if (!ExpectedParent) {
5938 return true;
5939 }
5940 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005941 }
5942
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005943 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005944 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005945
5946 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005947 ASTContext &Context;
5948 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005949 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005950};
5951
5952}
5953
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005954/// \brief Generate diagnostics for an invalid function redeclaration.
5955///
5956/// This routine handles generating the diagnostic messages for an invalid
5957/// function redeclaration, including finding possible similar declarations
5958/// or performing typo correction if there are no previous declarations with
5959/// the same name.
5960///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00005961/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005962/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00005963static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00005964 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00005965 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00005966 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005967 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005968 SmallVector<unsigned, 1> MismatchedParams;
5969 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00005970 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00005971 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00005972 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
5973 : diag::err_member_decl_does_not_match;
5974 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
5975 IsLocalFriend ? Sema::LookupLocalFriendName
5976 : Sema::LookupOrdinaryName,
5977 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00005978
5979 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00005980 if (IsLocalFriend)
5981 SemaRef.LookupName(Prev, S);
5982 else
5983 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00005984 assert(!Prev.isAmbiguous() &&
5985 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005986 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005987 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
5988 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00005989 if (!Prev.empty()) {
5990 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
5991 Func != FuncEnd; ++Func) {
5992 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00005993 if (FD &&
5994 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00005995 // Add 1 to the index so that 0 can mean the mismatch didn't
5996 // involve a parameter
5997 unsigned ParamNum =
5998 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
5999 NearMatches.push_back(std::make_pair(FD, ParamNum));
6000 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006001 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006002 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006003 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006004 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6005 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6006 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006007 // Set up everything for the call to ActOnFunctionDeclarator
6008 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6009 ExtraArgs.D.getIdentifierLoc());
6010 Previous.clear();
6011 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006012 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6013 CDeclEnd = Correction.end();
6014 CDecl != CDeclEnd; ++CDecl) {
6015 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006016 if (FD && !FD->hasBody() &&
6017 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006018 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006019 }
6020 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006021 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006022
6023 NamedDecl *Result;
6024 // Retry building the function declaration with the new previous
6025 // declarations, and with errors suppressed.
6026 {
6027 // Trap errors.
6028 Sema::SFINAETrap Trap(SemaRef);
6029
6030 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6031 // pieces need to verify the typo-corrected C++ declaration and hopefully
6032 // eliminate the need for the parameter pack ExtraArgs.
6033 Result = SemaRef.ActOnFunctionDeclarator(
6034 ExtraArgs.S, ExtraArgs.D,
6035 Correction.getCorrectionDecl()->getDeclContext(),
6036 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6037 ExtraArgs.AddToScope);
6038
6039 if (Trap.hasErrorOccurred())
6040 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006041 }
Richard Smith2d670972013-08-17 00:46:16 +00006042
6043 if (Result) {
6044 // Determine which correction we picked.
6045 Decl *Canonical = Result->getCanonicalDecl();
6046 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6047 I != E; ++I)
6048 if ((*I)->getCanonicalDecl() == Canonical)
6049 Correction.setCorrectionDecl(*I);
6050
6051 SemaRef.diagnoseTypo(
6052 Correction,
6053 SemaRef.PDiag(IsLocalFriend
6054 ? diag::err_no_matching_local_friend_suggest
6055 : diag::err_member_decl_does_not_match_suggest)
6056 << Name << NewDC << IsDefinition);
6057 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006058 }
Richard Smith2d670972013-08-17 00:46:16 +00006059
6060 // Pretend the typo correction never occurred
6061 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6062 ExtraArgs.D.getIdentifierLoc());
6063 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6064 Previous.clear();
6065 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006066 }
6067
Richard Smith2d670972013-08-17 00:46:16 +00006068 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6069 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006070
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006071 bool NewFDisConst = false;
6072 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006073 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006074
Craig Topper8bc99dd2013-07-04 03:15:42 +00006075 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006076 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6077 NearMatch != NearMatchEnd; ++NearMatch) {
6078 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006079 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6080 bool FDisConst = MD && MD->isConst();
6081 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006082
Richard Smitha41c97a2013-09-20 01:15:31 +00006083 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006084 if (unsigned Idx = NearMatch->second) {
6085 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006086 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6087 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006088 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6089 : diag::note_local_decl_close_param_match)
6090 << Idx << FDParam->getType()
6091 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006092 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006093 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006094 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006095 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006096 SemaRef.Diag(FD->getLocation(),
6097 IsMember ? diag::note_member_def_close_match
6098 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006099 }
Richard Smith2d670972013-08-17 00:46:16 +00006100 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006101}
6102
David Blaikied662a792011-10-19 22:56:21 +00006103static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6104 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006105 switch (D.getDeclSpec().getStorageClassSpec()) {
6106 default: llvm_unreachable("Unknown storage class!");
6107 case DeclSpec::SCS_auto:
6108 case DeclSpec::SCS_register:
6109 case DeclSpec::SCS_mutable:
6110 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6111 diag::err_typecheck_sclass_func);
6112 D.setInvalidType();
6113 break;
6114 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006115 case DeclSpec::SCS_extern:
6116 if (D.getDeclSpec().isExternInLinkageSpec())
6117 return SC_None;
6118 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006119 case DeclSpec::SCS_static: {
6120 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6121 // C99 6.7.1p5:
6122 // The declaration of an identifier for a function that has
6123 // block scope shall have no explicit storage-class specifier
6124 // other than extern
6125 // See also (C++ [dcl.stc]p4).
6126 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6127 diag::err_static_block_func);
6128 break;
6129 } else
6130 return SC_Static;
6131 }
6132 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6133 }
6134
6135 // No explicit storage class has already been returned
6136 return SC_None;
6137}
6138
6139static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6140 DeclContext *DC, QualType &R,
6141 TypeSourceInfo *TInfo,
6142 FunctionDecl::StorageClass SC,
6143 bool &IsVirtualOkay) {
6144 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6145 DeclarationName Name = NameInfo.getName();
6146
6147 FunctionDecl *NewFD = 0;
6148 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006149
David Blaikie4e4d0842012-03-11 07:00:24 +00006150 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006151 // Determine whether the function was written with a
6152 // prototype. This true when:
6153 // - there is a prototype in the declarator, or
6154 // - the type R of the function is some kind of typedef or other reference
6155 // to a type name (which eventually refers to a function type).
6156 bool HasPrototype =
6157 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6158 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6159
David Blaikied662a792011-10-19 22:56:21 +00006160 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006161 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006162 TInfo, SC, isInline,
6163 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006164 if (D.isInvalidType())
6165 NewFD->setInvalidDecl();
6166
6167 // Set the lexical context.
6168 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6169
6170 return NewFD;
6171 }
6172
6173 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6174 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6175
6176 // Check that the return type is not an abstract class type.
6177 // For record types, this is done by the AbstractClassUsageDiagnoser once
6178 // the class has been completely parsed.
6179 if (!DC->isRecord() &&
6180 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6181 R->getAs<FunctionType>()->getResultType(),
6182 diag::err_abstract_type_in_decl,
6183 SemaRef.AbstractReturnType))
6184 D.setInvalidType();
6185
6186 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6187 // This is a C++ constructor declaration.
6188 assert(DC->isRecord() &&
6189 "Constructors can only be declared in a member context");
6190
6191 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6192 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006193 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006194 R, TInfo, isExplicit, isInline,
6195 /*isImplicitlyDeclared=*/false,
6196 isConstexpr);
6197
6198 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6199 // This is a C++ destructor declaration.
6200 if (DC->isRecord()) {
6201 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6202 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6203 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6204 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006205 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006206 NameInfo, R, TInfo, isInline,
6207 /*isImplicitlyDeclared=*/false);
6208
6209 // If the class is complete, then we now create the implicit exception
6210 // specification. If the class is incomplete or dependent, we can't do
6211 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006212 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006213 Record->getDefinition() && !Record->isBeingDefined() &&
6214 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6215 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6216 }
6217
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006218 // The Microsoft ABI requires that we perform the destructor body
6219 // checks (i.e. operator delete() lookup) at every declaration, as
6220 // any translation unit may need to emit a deleting destructor.
6221 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6222 !Record->isDependentType() && Record->getDefinition() &&
6223 !Record->isBeingDefined()) {
6224 SemaRef.CheckDestructor(NewDD);
6225 }
6226
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006227 IsVirtualOkay = true;
6228 return NewDD;
6229
6230 } else {
6231 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6232 D.setInvalidType();
6233
6234 // Create a FunctionDecl to satisfy the function definition parsing
6235 // code path.
6236 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006237 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006238 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006239 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006240 /*hasPrototype=*/true, isConstexpr);
6241 }
6242
6243 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6244 if (!DC->isRecord()) {
6245 SemaRef.Diag(D.getIdentifierLoc(),
6246 diag::err_conv_function_not_member);
6247 return 0;
6248 }
6249
6250 SemaRef.CheckConversionDeclarator(D, R, SC);
6251 IsVirtualOkay = true;
6252 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006253 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006254 R, TInfo, isInline, isExplicit,
6255 isConstexpr, SourceLocation());
6256
6257 } else if (DC->isRecord()) {
6258 // If the name of the function is the same as the name of the record,
6259 // then this must be an invalid constructor that has a return type.
6260 // (The parser checks for a return type and makes the declarator a
6261 // constructor if it has no return type).
6262 if (Name.getAsIdentifierInfo() &&
6263 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6264 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6265 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6266 << SourceRange(D.getIdentifierLoc());
6267 return 0;
6268 }
6269
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006270 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006271 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6272 cast<CXXRecordDecl>(DC),
6273 D.getLocStart(), NameInfo, R,
6274 TInfo, SC, isInline,
6275 isConstexpr, SourceLocation());
6276 IsVirtualOkay = !Ret->isStatic();
6277 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006278 } else {
6279 // Determine whether the function was written with a
6280 // prototype. This true when:
6281 // - we're in C++ (where every function has a prototype),
6282 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006283 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006284 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006285 true/*HasPrototype*/, isConstexpr);
6286 }
6287}
6288
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006289void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6290 // In C++, the empty parameter-type-list must be spelled "void"; a
6291 // typedef of void is not permitted.
6292 if (getLangOpts().CPlusPlus &&
6293 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6294 bool IsTypeAlias = false;
6295 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6296 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6297 else if (const TemplateSpecializationType *TST =
6298 Param->getType()->getAs<TemplateSpecializationType>())
6299 IsTypeAlias = TST->isTypeAlias();
6300 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6301 << IsTypeAlias;
6302 }
6303}
6304
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006305enum OpenCLParamType {
6306 ValidKernelParam,
6307 PtrPtrKernelParam,
6308 PtrKernelParam,
6309 InvalidKernelParam,
6310 RecordKernelParam
6311};
6312
6313static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6314 if (PT->isPointerType()) {
6315 QualType PointeeType = PT->getPointeeType();
6316 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6317 }
6318
6319 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6320 // be used as builtin types.
6321
6322 if (PT->isImageType())
6323 return PtrKernelParam;
6324
6325 if (PT->isBooleanType())
6326 return InvalidKernelParam;
6327
6328 if (PT->isEventT())
6329 return InvalidKernelParam;
6330
6331 if (PT->isHalfType())
6332 return InvalidKernelParam;
6333
6334 if (PT->isRecordType())
6335 return RecordKernelParam;
6336
6337 return ValidKernelParam;
6338}
6339
6340static void checkIsValidOpenCLKernelParameter(
6341 Sema &S,
6342 Declarator &D,
6343 ParmVarDecl *Param,
6344 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6345 QualType PT = Param->getType();
6346
6347 // Cache the valid types we encounter to avoid rechecking structs that are
6348 // used again
6349 if (ValidTypes.count(PT.getTypePtr()))
6350 return;
6351
6352 switch (getOpenCLKernelParameterType(PT)) {
6353 case PtrPtrKernelParam:
6354 // OpenCL v1.2 s6.9.a:
6355 // A kernel function argument cannot be declared as a
6356 // pointer to a pointer type.
6357 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6358 D.setInvalidType();
6359 return;
6360
6361 // OpenCL v1.2 s6.9.k:
6362 // Arguments to kernel functions in a program cannot be declared with the
6363 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6364 // uintptr_t or a struct and/or union that contain fields declared to be
6365 // one of these built-in scalar types.
6366
6367 case InvalidKernelParam:
6368 // OpenCL v1.2 s6.8 n:
6369 // A kernel function argument cannot be declared
6370 // of event_t type.
6371 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6372 D.setInvalidType();
6373 return;
6374
6375 case PtrKernelParam:
6376 case ValidKernelParam:
6377 ValidTypes.insert(PT.getTypePtr());
6378 return;
6379
6380 case RecordKernelParam:
6381 break;
6382 }
6383
6384 // Track nested structs we will inspect
6385 SmallVector<const Decl *, 4> VisitStack;
6386
6387 // Track where we are in the nested structs. Items will migrate from
6388 // VisitStack to HistoryStack as we do the DFS for bad field.
6389 SmallVector<const FieldDecl *, 4> HistoryStack;
6390 HistoryStack.push_back((const FieldDecl *) 0);
6391
6392 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6393 VisitStack.push_back(PD);
6394
6395 assert(VisitStack.back() && "First decl null?");
6396
6397 do {
6398 const Decl *Next = VisitStack.pop_back_val();
6399 if (!Next) {
6400 assert(!HistoryStack.empty());
6401 // Found a marker, we have gone up a level
6402 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6403 ValidTypes.insert(Hist->getType().getTypePtr());
6404
6405 continue;
6406 }
6407
6408 // Adds everything except the original parameter declaration (which is not a
6409 // field itself) to the history stack.
6410 const RecordDecl *RD;
6411 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6412 HistoryStack.push_back(Field);
6413 RD = Field->getType()->castAs<RecordType>()->getDecl();
6414 } else {
6415 RD = cast<RecordDecl>(Next);
6416 }
6417
6418 // Add a null marker so we know when we've gone back up a level
6419 VisitStack.push_back((const Decl *) 0);
6420
6421 for (RecordDecl::field_iterator I = RD->field_begin(),
6422 E = RD->field_end(); I != E; ++I) {
6423 const FieldDecl *FD = *I;
6424 QualType QT = FD->getType();
6425
6426 if (ValidTypes.count(QT.getTypePtr()))
6427 continue;
6428
6429 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6430 if (ParamType == ValidKernelParam)
6431 continue;
6432
6433 if (ParamType == RecordKernelParam) {
6434 VisitStack.push_back(FD);
6435 continue;
6436 }
6437
6438 // OpenCL v1.2 s6.9.p:
6439 // Arguments to kernel functions that are declared to be a struct or union
6440 // do not allow OpenCL objects to be passed as elements of the struct or
6441 // union.
6442 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6443 S.Diag(Param->getLocation(),
6444 diag::err_record_with_pointers_kernel_param)
6445 << PT->isUnionType()
6446 << PT;
6447 } else {
6448 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6449 }
6450
6451 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6452 << PD->getDeclName();
6453
6454 // We have an error, now let's go back up through history and show where
6455 // the offending field came from
6456 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6457 E = HistoryStack.end(); I != E; ++I) {
6458 const FieldDecl *OuterField = *I;
6459 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6460 << OuterField->getType();
6461 }
6462
6463 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6464 << QT->isPointerType()
6465 << QT;
6466 D.setInvalidType();
6467 return;
6468 }
6469 } while (!VisitStack.empty());
6470}
6471
Mike Stump1eb44332009-09-09 15:08:12 +00006472NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006473Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006474 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006475 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006476 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006477 QualType R = TInfo->getType();
6478
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006479 assert(R.getTypePtr()->isFunctionType());
6480
Abramo Bagnara25777432010-08-11 22:01:17 +00006481 // TODO: consider using NameInfo for diagnostic.
6482 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6483 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006484 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006485
Richard Smithec642442013-04-12 22:46:28 +00006486 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6487 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6488 diag::err_invalid_thread)
6489 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006490
Reid Kleckneref072032013-08-27 23:08:25 +00006491 if (DC->isRecord() &&
6492 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
6493 !D.getDeclSpec().isFriendSpecified())
6494 adjustMemberFunctionCC(R);
6495
Douglas Gregor3922ed02010-12-10 19:28:19 +00006496 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006497 FunctionTemplateDecl *FunctionTemplate = 0;
6498 bool isExplicitSpecialization = false;
6499 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006500
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006501 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006502 bool HasExplicitTemplateArgs = false;
6503 TemplateArgumentListInfo TemplateArgs;
6504
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006505 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006506
Richard Smitha41c97a2013-09-20 01:15:31 +00006507 DeclContext *OriginalDC = DC;
6508 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6509
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006510 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6511 isVirtualOkay);
6512 if (!NewFD) return 0;
6513
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006514 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6515 NewFD->setTopLevelDeclInObjCContainer();
6516
Richard Smitha41c97a2013-09-20 01:15:31 +00006517 // Set the lexical context. If this is a function-scope declaration, or has a
6518 // C++ scope specifier, or is the object of a friend declaration, the lexical
6519 // context will be different from the semantic context.
6520 NewFD->setLexicalDeclContext(CurContext);
6521
6522 if (IsLocalExternDecl)
6523 NewFD->setLocalExternDecl();
6524
David Blaikie4e4d0842012-03-11 07:00:24 +00006525 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006526 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006527 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6528 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006529 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006530 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006531 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006532 // C++ [class.friend]p5
6533 // A function can be defined in a friend declaration of a
6534 // class . . . . Such a function is implicitly inline.
6535 NewFD->setImplicitlyInline();
6536 }
6537
John McCalle402e722012-09-25 07:32:39 +00006538 // If this is a method defined in an __interface, and is not a constructor
6539 // or an overloaded operator, then set the pure flag (isVirtual will already
6540 // return true).
6541 if (const CXXRecordDecl *Parent =
6542 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6543 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006544 NewFD->setPure(true);
6545 }
6546
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006547 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006548 isExplicitSpecialization = false;
6549 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006550 if (D.isInvalidType())
6551 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006552
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006553 // Match up the template parameter lists with the scope specifier, then
6554 // determine whether we have a template or a template specialization.
6555 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006556 if (TemplateParameterList *TemplateParams =
6557 MatchTemplateParametersToScopeSpecifier(
6558 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6559 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6560 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006561 if (TemplateParams->size() > 0) {
6562 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006563
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006564 // Check that we can declare a template here.
6565 if (CheckTemplateDeclScope(S, TemplateParams))
6566 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006567
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006568 // A destructor cannot be a template.
6569 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6570 Diag(NewFD->getLocation(), diag::err_destructor_template);
6571 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006572 }
Douglas Gregor20606502011-10-14 15:31:12 +00006573
6574 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006575 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006576 // now that we know what the current instantiation is.
6577 if (DC->isDependentContext()) {
6578 ContextRAII SavedContext(*this, DC);
6579 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6580 Invalid = true;
6581 }
6582
John McCall5fd378b2010-03-24 08:27:58 +00006583
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006584 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6585 NewFD->getLocation(),
6586 Name, TemplateParams,
6587 NewFD);
6588 FunctionTemplate->setLexicalDeclContext(CurContext);
6589 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6590
6591 // For source fidelity, store the other template param lists.
6592 if (TemplateParamLists.size() > 1) {
6593 NewFD->setTemplateParameterListsInfo(Context,
6594 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006595 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006596 }
6597 } else {
6598 // This is a function template specialization.
6599 isFunctionTemplateSpecialization = true;
6600 // For source fidelity, store all the template param lists.
6601 NewFD->setTemplateParameterListsInfo(Context,
6602 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006603 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006604
6605 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6606 if (isFriend) {
6607 // We want to remove the "template<>", found here.
6608 SourceRange RemoveRange = TemplateParams->getSourceRange();
6609
6610 // If we remove the template<> and the name is not a
6611 // template-id, we're actually silently creating a problem:
6612 // the friend declaration will refer to an untemplated decl,
6613 // and clearly the user wants a template specialization. So
6614 // we need to insert '<>' after the name.
6615 SourceLocation InsertLoc;
6616 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6617 InsertLoc = D.getName().getSourceRange().getEnd();
6618 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6619 }
6620
6621 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6622 << Name << RemoveRange
6623 << FixItHint::CreateRemoval(RemoveRange)
6624 << FixItHint::CreateInsertion(InsertLoc, "<>");
6625 }
6626 }
6627 }
6628 else {
6629 // All template param lists were matched against the scope specifier:
6630 // this is NOT (an explicit specialization of) a template.
6631 if (TemplateParamLists.size() > 0)
6632 // For source fidelity, store all the template param lists.
6633 NewFD->setTemplateParameterListsInfo(Context,
6634 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006635 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006636 }
6637
6638 if (Invalid) {
6639 NewFD->setInvalidDecl();
6640 if (FunctionTemplate)
6641 FunctionTemplate->setInvalidDecl();
6642 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006643
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006644 // C++ [dcl.fct.spec]p5:
6645 // The virtual specifier shall only be used in declarations of
6646 // nonstatic class member functions that appear within a
6647 // member-specification of a class declaration; see 10.3.
6648 //
6649 if (isVirtual && !NewFD->isInvalidDecl()) {
6650 if (!isVirtualOkay) {
6651 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6652 diag::err_virtual_non_function);
6653 } else if (!CurContext->isRecord()) {
6654 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006655 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6656 diag::err_virtual_out_of_class)
6657 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6658 } else if (NewFD->getDescribedFunctionTemplate()) {
6659 // C++ [temp.mem]p3:
6660 // A member function template shall not be virtual.
6661 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6662 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006663 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6664 } else {
6665 // Okay: Add virtual to the method.
6666 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006667 }
Richard Smith60e141e2013-05-04 07:00:32 +00006668
6669 if (getLangOpts().CPlusPlus1y &&
6670 NewFD->getResultType()->isUndeducedType())
6671 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006672 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006673
Richard Smith37e849a2013-08-14 20:16:31 +00006674 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6675 NewFD->getResultType()->isUndeducedType()) {
6676 // If the function template is referenced directly (for instance, as a
6677 // member of the current instantiation), pretend it has a dependent type.
6678 // This is not really justified by the standard, but is the only sane
6679 // thing to do.
6680 const FunctionProtoType *FPT =
6681 NewFD->getType()->castAs<FunctionProtoType>();
6682 QualType Result = SubstAutoType(FPT->getResultType(),
6683 Context.DependentTy);
6684 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6685 FPT->getExtProtoInfo()));
6686 }
6687
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006688 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006689 // The inline specifier shall not appear on a block scope function
6690 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006691 if (isInline && !NewFD->isInvalidDecl()) {
6692 if (CurContext->isFunctionOrMethod()) {
6693 // 'inline' is not allowed on block scope function declaration.
6694 Diag(D.getDeclSpec().getInlineSpecLoc(),
6695 diag::err_inline_declaration_block_scope) << Name
6696 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6697 }
6698 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006699
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006700 // C++ [dcl.fct.spec]p6:
6701 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006702 // constructor or conversion function within its class definition;
6703 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006704 if (isExplicit && !NewFD->isInvalidDecl()) {
6705 if (!CurContext->isRecord()) {
6706 // 'explicit' was specified outside of the class.
6707 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6708 diag::err_explicit_out_of_class)
6709 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6710 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6711 !isa<CXXConversionDecl>(NewFD)) {
6712 // 'explicit' was specified on a function that wasn't a constructor
6713 // or conversion function.
6714 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6715 diag::err_explicit_non_ctor_or_conv_function)
6716 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6717 }
6718 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006719
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006720 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006721 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006722 // are implicitly inline.
6723 NewFD->setImplicitlyInline();
6724
Richard Smith21c8fa82013-01-14 05:37:29 +00006725 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006726 // be either constructors or to return a literal type. Therefore,
6727 // destructors cannot be declared constexpr.
6728 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006729 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006730 }
6731
Douglas Gregor8d267c52011-09-09 02:06:17 +00006732 // If __module_private__ was specified, mark the function accordingly.
6733 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006734 if (isFunctionTemplateSpecialization) {
6735 SourceLocation ModulePrivateLoc
6736 = D.getDeclSpec().getModulePrivateSpecLoc();
6737 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6738 << 0
6739 << FixItHint::CreateRemoval(ModulePrivateLoc);
6740 } else {
6741 NewFD->setModulePrivate();
6742 if (FunctionTemplate)
6743 FunctionTemplate->setModulePrivate();
6744 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006745 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006746
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006747 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006748 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006749 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006750 FunctionTemplate->setAccess(AS_public);
6751 }
Richard Smith22050f22013-07-17 23:53:16 +00006752 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006753 NewFD->setAccess(AS_public);
6754 }
6755
Douglas Gregor45fa5602011-11-07 20:56:01 +00006756 // If a function is defined as defaulted or deleted, mark it as such now.
6757 switch (D.getFunctionDefinitionKind()) {
6758 case FDK_Declaration:
6759 case FDK_Definition:
6760 break;
6761
6762 case FDK_Defaulted:
6763 NewFD->setDefaulted();
6764 break;
6765
6766 case FDK_Deleted:
6767 NewFD->setDeletedAsWritten();
6768 break;
6769 }
6770
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006771 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6772 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006773 // C++ [class.mfct]p2:
6774 // A member function may be defined (8.4) in its class definition, in
6775 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006776 NewFD->setImplicitlyInline();
6777 }
6778
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006779 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6780 !CurContext->isRecord()) {
6781 // C++ [class.static]p1:
6782 // A data or function member of a class may be declared static
6783 // in a class definition, in which case it is a static member of
6784 // the class.
6785
6786 // Complain about the 'static' specifier if it's on an out-of-line
6787 // member function definition.
6788 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6789 diag::err_static_out_of_line)
6790 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6791 }
Richard Smith444d3842012-10-20 08:26:51 +00006792
6793 // C++11 [except.spec]p15:
6794 // A deallocation function with no exception-specification is treated
6795 // as if it were specified with noexcept(true).
6796 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6797 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6798 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006799 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006800 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6801 EPI.ExceptionSpecType = EST_BasicNoexcept;
6802 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006803 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006804 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006805 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006806
6807 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006808 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006809 isExplicitSpecialization ||
6810 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006811
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006812 // Handle GNU asm-label extension (encoded as an attribute).
6813 if (Expr *E = (Expr*) D.getAsmLabel()) {
6814 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006815 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006816 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6817 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006818 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6819 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6820 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6821 if (I != ExtnameUndeclaredIdentifiers.end()) {
6822 NewFD->addAttr(I->second);
6823 ExtnameUndeclaredIdentifiers.erase(I);
6824 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006825 }
6826
Chris Lattner2dbd2852009-04-25 06:12:16 +00006827 // Copy the parameter declarations from the declarator D to the function
6828 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006829 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006830 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006831 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006832
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006833 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6834 // function that takes no arguments, not a function that takes a
6835 // single void argument.
6836 // We let through "const void" here because Sema::GetTypeForDeclarator
6837 // already checks for that case.
6838 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6839 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006840 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006841 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006842 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006843 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006844 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006845 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006846 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6847 Param->setDeclContext(NewFD);
6848 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006849
6850 if (Param->isInvalidDecl())
6851 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006852 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006853 }
Mike Stump1eb44332009-09-09 15:08:12 +00006854
John McCall183700f2009-09-21 23:43:11 +00006855 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006856 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006857 // following example, we'll need to synthesize (unnamed)
6858 // parameters for use in the declaration.
6859 //
6860 // @code
6861 // typedef void fn(int);
6862 // fn f;
6863 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006864
Chris Lattner1ad9b282009-04-25 06:03:53 +00006865 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006866 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6867 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006868 ParmVarDecl *Param =
6869 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006870 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006871 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006872 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006873 } else {
6874 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6875 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006876 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006877
Chris Lattner2dbd2852009-04-25 06:12:16 +00006878 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006879 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006880
James Molloy16f1f712012-02-29 10:24:19 +00006881 // Find all anonymous symbols defined during the declaration of this function
6882 // and add to NewFD. This lets us track decls such 'enum Y' in:
6883 //
6884 // void f(enum Y {AA} x) {}
6885 //
6886 // which would otherwise incorrectly end up in the translation unit scope.
6887 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6888 DeclsInPrototypeScope.clear();
6889
Richard Smith7586a6e2013-01-30 05:45:05 +00006890 if (D.getDeclSpec().isNoreturnSpecified())
6891 NewFD->addAttr(
6892 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6893 Context));
6894
Richard Smithb03a9df2012-03-13 05:56:40 +00006895 // Functions returning a variably modified type violate C99 6.7.5.2p2
6896 // because all functions have linkage.
6897 if (!NewFD->isInvalidDecl() &&
6898 NewFD->getResultType()->isVariablyModifiedType()) {
6899 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6900 NewFD->setInvalidDecl();
6901 }
6902
Rafael Espindola98ae8342012-05-10 02:50:16 +00006903 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006904 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006905
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006906 QualType RetType = NewFD->getResultType();
6907 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6908 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6909 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6910 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006911 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6912 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
6913 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6914 Context));
6915 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006916 }
6917
David Blaikie4e4d0842012-03-11 07:00:24 +00006918 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006919 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00006920 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00006921 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6922 CheckMain(NewFD, D.getDeclSpec());
6923
David Majnemere9f6f332013-09-16 22:44:20 +00006924 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6925 CheckMSVCRTEntryPoint(NewFD);
6926
David Majnemerc371db62013-07-06 02:13:46 +00006927 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00006928 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6929 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00006930 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00006931 // Make graceful recovery from an invalid redeclaration.
6932 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006933 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006934 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
6935 "previous declaration set still overloaded");
6936 } else {
6937 // If the declarator is a template-id, translate the parser's template
6938 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006939 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6940 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6941 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6942 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00006943 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006944 TemplateId->NumArgs);
6945 translateTemplateArguments(TemplateArgsPtr,
6946 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00006947
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006948 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00006949
Douglas Gregor89b9f102011-06-06 15:22:55 +00006950 if (NewFD->isInvalidDecl()) {
6951 HasExplicitTemplateArgs = false;
6952 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00006953 // Function template with explicit template arguments.
6954 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
6955 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
6956
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006957 HasExplicitTemplateArgs = false;
6958 } else if (!isFunctionTemplateSpecialization &&
6959 !D.getDeclSpec().isFriendSpecified()) {
6960 // We have encountered something that the user meant to be a
6961 // specialization (because it has explicitly-specified template
6962 // arguments) but that was not introduced with a "template<>" (or had
6963 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00006964 // FIXME: Differentiate between attempts for explicit instantiations
6965 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006966 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
6967 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
6968 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00006969 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00006970 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006971 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00006972 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006973 // "friend void foo<>(int);" is an implicit specialization decl.
6974 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00006975 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006976 } else if (isFriend && isFunctionTemplateSpecialization) {
6977 // This combination is only possible in a recovery case; the user
6978 // wrote something like:
6979 // template <> friend void foo(int);
6980 // which we're recovering from as if the user had written:
6981 // friend void foo<>(int);
6982 // Go ahead and fake up a template id.
6983 HasExplicitTemplateArgs = true;
6984 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
6985 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00006986 }
John McCall29ae6e52010-10-13 05:45:15 +00006987
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006988 // If it's a friend (and only if it's a friend), it's possible
6989 // that either the specialized function type or the specialized
6990 // template is dependent, and therefore matching will fail. In
6991 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00006992 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006993 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00006994 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
6995 TemplateSpecializationType::anyDependentTemplateArguments(
6996 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
6997 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006998 assert(HasExplicitTemplateArgs &&
6999 "friend function specialization without template args");
7000 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7001 Previous))
7002 NewFD->setInvalidDecl();
7003 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007004 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007005 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007006 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007007 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007008 diag::ext_function_specialization_in_class :
7009 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007010 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007011 } else if (CheckFunctionTemplateSpecialization(NewFD,
7012 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7013 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007014 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007015
7016 // C++ [dcl.stc]p1:
7017 // A storage-class-specifier shall not be specified in an explicit
7018 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007019 FunctionTemplateSpecializationInfo *Info =
7020 NewFD->getTemplateSpecializationInfo();
7021 if (Info && SC != SC_None) {
7022 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007023 Diag(NewFD->getLocation(),
7024 diag::err_explicit_specialization_inconsistent_storage_class)
7025 << SC
7026 << FixItHint::CreateRemoval(
7027 D.getDeclSpec().getStorageClassSpecLoc());
7028
7029 else
7030 Diag(NewFD->getLocation(),
7031 diag::ext_explicit_specialization_storage_class)
7032 << FixItHint::CreateRemoval(
7033 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007034 }
7035
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007036 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7037 if (CheckMemberSpecialization(NewFD, Previous))
7038 NewFD->setInvalidDecl();
7039 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007040
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007041 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007042 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007043 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7044 CheckMain(NewFD, D.getDeclSpec());
7045
David Majnemere9f6f332013-09-16 22:44:20 +00007046 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7047 CheckMSVCRTEntryPoint(NewFD);
7048
David Blaikie14068e82011-09-08 06:33:04 +00007049 if (NewFD->isInvalidDecl()) {
7050 // If this is a class member, mark the class invalid immediately.
7051 // This avoids some consistency errors later.
7052 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7053 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007054 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007055 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7056 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007057 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007058
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007059 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007060 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7061 "previous declaration set still overloaded");
7062
7063 NamedDecl *PrincipalDecl = (FunctionTemplate
7064 ? cast<NamedDecl>(FunctionTemplate)
7065 : NewFD);
7066
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007067 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007068 AccessSpecifier Access = AS_public;
7069 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007070 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007071
7072 NewFD->setAccess(Access);
7073 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007074 }
7075
7076 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7077 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7078 PrincipalDecl->setNonMemberOperator();
7079
7080 // If we have a function template, check the template parameter
7081 // list. This will check and merge default template arguments.
7082 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007083 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007084 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007085 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007086 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007087 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007088 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007089 ? TPC_FriendFunctionTemplateDefinition
7090 : TPC_FriendFunctionTemplate)
7091 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007092 DC && DC->isRecord() &&
7093 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007094 ? TPC_ClassTemplateMember
7095 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007096 }
7097
7098 if (NewFD->isInvalidDecl()) {
7099 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007100 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007101 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007102 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007103 // Fake up an access specifier if it's supposed to be a class member.
7104 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7105 NewFD->setAccess(AS_public);
7106
7107 // Qualified decls generally require a previous declaration.
7108 if (D.getCXXScopeSpec().isSet()) {
7109 // ...with the major exception of templated-scope or
7110 // dependent-scope friend declarations.
7111
7112 // TODO: we currently also suppress this check in dependent
7113 // contexts because (1) the parameter depth will be off when
7114 // matching friend templates and (2) we might actually be
7115 // selecting a friend based on a dependent factor. But there
7116 // are situations where these conditions don't apply and we
7117 // can actually do this check immediately.
7118 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007119 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007120 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7121 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007122 // ignore these
7123 } else {
7124 // The user tried to provide an out-of-line definition for a
7125 // function that is a member of a class or namespace, but there
7126 // was no such member function declared (C++ [class.mfct]p2,
7127 // C++ [namespace.memdef]p2). For example:
7128 //
7129 // class X {
7130 // void f() const;
7131 // };
7132 //
7133 // void X::f() { } // ill-formed
7134 //
7135 // Complain about this problem, and attempt to suggest close
7136 // matches (e.g., those that differ only in cv-qualifiers and
7137 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007138
Richard Smith4e9686b2013-08-09 04:35:01 +00007139 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7140 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007141 AddToScope = ExtraArgs.AddToScope;
7142 return Result;
7143 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007144 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007145
7146 // Unqualified local friend declarations are required to resolve
7147 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007148 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007149 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7150 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007151 AddToScope = ExtraArgs.AddToScope;
7152 return Result;
7153 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007154 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007155
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007156 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007157 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007158 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007159 // An out-of-line member function declaration must also be a
7160 // definition (C++ [dcl.meaning]p1).
7161 // Note that this is not the case for explicit specializations of
7162 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007163 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7164 // extension for compatibility with old SWIG code which likes to
7165 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007166 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7167 << D.getCXXScopeSpec().getRange();
7168 }
7169 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007170
Rafael Espindola65611bf2013-03-02 21:41:48 +00007171 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007172 checkAttributesAfterMerging(*this, *NewFD);
7173
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007174 AddKnownFunctionAttributes(NewFD);
7175
Douglas Gregord9455382010-08-06 13:50:58 +00007176 if (NewFD->hasAttr<OverloadableAttr>() &&
7177 !NewFD->getType()->getAs<FunctionProtoType>()) {
7178 Diag(NewFD->getLocation(),
7179 diag::err_attribute_overloadable_no_prototype)
7180 << NewFD;
7181
7182 // Turn this into a variadic function with no parameters.
7183 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007184 FunctionProtoType::ExtProtoInfo EPI(
7185 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007186 EPI.Variadic = true;
7187 EPI.ExtInfo = FT->getExtInfo();
7188
Dmitri Gribenko55431692013-05-05 00:41:58 +00007189 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007190 NewFD->setType(R);
7191 }
7192
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007193 // If there's a #pragma GCC visibility in scope, and this isn't a class
7194 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007195 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007196 AddPushedVisibilityAttribute(NewFD);
7197
John McCall8dfac0b2011-09-30 05:12:12 +00007198 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7199 // marking the function.
7200 AddCFAuditedAttribute(NewFD);
7201
Richard Smithaa4bc182013-06-30 09:48:50 +00007202 // If this is the first declaration of an extern C variable, update
7203 // the map of such variables.
7204 if (!NewFD->getPreviousDecl() && !NewFD->isInvalidDecl() &&
7205 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007206 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007207
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007208 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007209 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007210
David Blaikie4e4d0842012-03-11 07:00:24 +00007211 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007212 if (FunctionTemplate) {
7213 if (NewFD->isInvalidDecl())
7214 FunctionTemplate->setInvalidDecl();
7215 return FunctionTemplate;
7216 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007217 }
Mike Stump1eb44332009-09-09 15:08:12 +00007218
Guy Benyeie6b9d802013-01-20 12:31:11 +00007219 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007220 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7221 if ((getLangOpts().OpenCLVersion >= 120)
7222 && (SC == SC_Static)) {
7223 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7224 D.setInvalidType();
7225 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007226
7227 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7228 if (!NewFD->getResultType()->isVoidType()) {
7229 Diag(D.getIdentifierLoc(),
7230 diag::err_expected_kernel_void_return_type);
7231 D.setInvalidType();
7232 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007233
7234 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007235 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7236 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007237 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007238 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007239 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007240 }
7241
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007242 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007243
David Blaikie4e4d0842012-03-11 07:00:24 +00007244 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007245 if (IdentifierInfo *II = NewFD->getIdentifier())
7246 if (!NewFD->isInvalidDecl() &&
7247 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7248 if (II->isStr("cudaConfigureCall")) {
7249 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7250 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7251
7252 Context.setcudaConfigureCallDecl(NewFD);
7253 }
7254 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007255
7256 // Here we have an function template explicit specialization at class scope.
7257 // The actually specialization will be postponed to template instatiation
7258 // time via the ClassScopeFunctionSpecializationDecl node.
7259 if (isDependentClassScopeExplicitSpecialization) {
7260 ClassScopeFunctionSpecializationDecl *NewSpec =
7261 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007262 Context, CurContext, SourceLocation(),
7263 cast<CXXMethodDecl>(NewFD),
7264 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007265 CurContext->addDecl(NewSpec);
7266 AddToScope = false;
7267 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007268
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007269 return NewFD;
7270}
7271
7272/// \brief Perform semantic checking of a new function declaration.
7273///
7274/// Performs semantic analysis of the new function declaration
7275/// NewFD. This routine performs all semantic checking that does not
7276/// require the actual declarator involved in the declaration, and is
7277/// used both for the declaration of functions as they are parsed
7278/// (called via ActOnDeclarator) and for the declaration of functions
7279/// that have been instantiated via C++ template instantiation (called
7280/// via InstantiateDecl).
7281///
James Dennettefce31f2012-06-22 08:10:18 +00007282/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007283/// an explicit specialization of the previous declaration.
7284///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007285/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007286///
James Dennettefce31f2012-06-22 08:10:18 +00007287/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007288bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007289 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007290 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007291 assert(!NewFD->getResultType()->isVariablyModifiedType()
7292 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007293
Richard Smithdd9459f2013-08-13 18:18:50 +00007294 // Determine whether the type of this function should be merged with
7295 // a previous visible declaration. This never happens for functions in C++,
7296 // and always happens in C if the previous declaration was visible.
7297 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7298 !Previous.isShadowed();
7299
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007300 // Filter out any non-conflicting previous declarations.
7301 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7302
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007303 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007304 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007305
Douglas Gregor04495c82009-02-24 01:23:02 +00007306 // Merge or overload the declaration with an existing declaration of
7307 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007308 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007309 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007310 // a declaration that requires merging. If it's an overload,
7311 // there's no more work to do here; we'll just add the new
7312 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007313 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007314 NamedDecl *Candidate = Previous.getFoundDecl();
7315 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7316 Redeclaration = true;
7317 OldDecl = Candidate;
7318 }
John McCall871b2e72009-12-09 03:35:25 +00007319 } else {
John McCallad00b772010-06-16 08:42:20 +00007320 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7321 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007322 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007323 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007324 break;
7325
7326 case Ovl_NonFunction:
7327 Redeclaration = true;
7328 break;
7329
7330 case Ovl_Overload:
7331 Redeclaration = false;
7332 break;
John McCall68263142009-11-18 22:49:29 +00007333 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007334
David Blaikie4e4d0842012-03-11 07:00:24 +00007335 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007336 // If a function name is overloadable in C, then every function
7337 // with that name must be marked "overloadable".
7338 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7339 << Redeclaration << NewFD;
7340 NamedDecl *OverloadedDecl = 0;
7341 if (Redeclaration)
7342 OverloadedDecl = OldDecl;
7343 else if (!Previous.empty())
7344 OverloadedDecl = Previous.getRepresentativeDecl();
7345 if (OverloadedDecl)
7346 Diag(OverloadedDecl->getLocation(),
7347 diag::note_attribute_overloadable_prev_overload);
7348 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7349 Context));
7350 }
John McCall68263142009-11-18 22:49:29 +00007351 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007352 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007353
Richard Smithaa4bc182013-06-30 09:48:50 +00007354 // Check for a previous extern "C" declaration with this name.
7355 if (!Redeclaration &&
7356 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7357 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7358 if (!Previous.empty()) {
7359 // This is an extern "C" declaration with the same name as a previous
7360 // declaration, and thus redeclares that entity...
7361 Redeclaration = true;
7362 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007363 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007364
7365 // ... except in the presence of __attribute__((overloadable)).
7366 if (OldDecl->hasAttr<OverloadableAttr>()) {
7367 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7368 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7369 << Redeclaration << NewFD;
7370 Diag(Previous.getFoundDecl()->getLocation(),
7371 diag::note_attribute_overloadable_prev_overload);
7372 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7373 Context));
7374 }
7375 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7376 Redeclaration = false;
7377 OldDecl = 0;
7378 }
7379 }
7380 }
7381 }
7382
Richard Smith21c8fa82013-01-14 05:37:29 +00007383 // C++11 [dcl.constexpr]p8:
7384 // A constexpr specifier for a non-static member function that is not
7385 // a constructor declares that member function to be const.
7386 //
7387 // This needs to be delayed until we know whether this is an out-of-line
7388 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007389 //
7390 // This rule is not present in C++1y, so we produce a backwards
7391 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007392 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007393 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7394 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007395 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7396 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7397 if (FunctionTemplateDecl *OldTD =
7398 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7399 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7400 if (!OldMD || !OldMD->isStatic()) {
7401 const FunctionProtoType *FPT =
7402 MD->getType()->castAs<FunctionProtoType>();
7403 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7404 EPI.TypeQuals |= Qualifiers::Const;
7405 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007406 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007407
7408 // Warn that we did this, if we're not performing template instantiation.
7409 // In that case, we'll have warned already when the template was defined.
7410 if (ActiveTemplateInstantiations.empty()) {
7411 SourceLocation AddConstLoc;
7412 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7413 .IgnoreParens().getAs<FunctionTypeLoc>())
7414 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7415
7416 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7417 << FixItHint::CreateInsertion(AddConstLoc, " const");
7418 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007419 }
7420 }
7421
7422 if (Redeclaration) {
7423 // NewFD and OldDecl represent declarations that need to be
7424 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007425 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007426 NewFD->setInvalidDecl();
7427 return Redeclaration;
7428 }
7429
7430 Previous.clear();
7431 Previous.addDecl(OldDecl);
7432
7433 if (FunctionTemplateDecl *OldTemplateDecl
7434 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7435 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7436 FunctionTemplateDecl *NewTemplateDecl
7437 = NewFD->getDescribedFunctionTemplate();
7438 assert(NewTemplateDecl && "Template/non-template mismatch");
7439 if (CXXMethodDecl *Method
7440 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7441 Method->setAccess(OldTemplateDecl->getAccess());
7442 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007443 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007444
7445 // If this is an explicit specialization of a member that is a function
7446 // template, mark it as a member specialization.
7447 if (IsExplicitSpecialization &&
7448 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7449 NewTemplateDecl->setMemberSpecialization();
7450 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007451 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007452
7453 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007454 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007455 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007456
7457 if (isa<CXXMethodDecl>(NewFD)) {
7458 // A valid redeclaration of a C++ method must be out-of-line,
7459 // but (unfortunately) it's not necessarily a definition
7460 // because of templates, which means that the previous
7461 // declaration is not necessarily from the class definition.
7462
7463 // For just setting the access, that doesn't matter.
7464 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7465 NewFD->setAccess(oldMethod->getAccess());
7466
7467 // Update the key-function state if necessary for this ABI.
7468 if (NewFD->isInlined() &&
7469 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7470 // setNonKeyFunction needs to work with the original
7471 // declaration from the class definition, and isVirtual() is
7472 // just faster in that case, so map back to that now.
7473 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration());
7474 if (oldMethod->isVirtual()) {
7475 Context.setNonKeyFunction(oldMethod);
7476 }
7477 }
7478 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007479 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007480 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007481
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007482 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007483 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007484 // C++-specific checks.
7485 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7486 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007487 } else if (CXXDestructorDecl *Destructor =
7488 dyn_cast<CXXDestructorDecl>(NewFD)) {
7489 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007490 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007491
Douglas Gregor4923aa22010-07-02 20:37:36 +00007492 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007493 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007494 if (!ClassType->isDependentType()) {
7495 DeclarationName Name
7496 = Context.DeclarationNames.getCXXDestructorName(
7497 Context.getCanonicalType(ClassType));
7498 if (NewFD->getDeclName() != Name) {
7499 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007500 NewFD->setInvalidDecl();
7501 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007502 }
7503 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007504 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007505 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007506 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007507 }
7508
7509 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7511 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007512 !Method->getDescribedFunctionTemplate() &&
7513 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007514 if (AddOverriddenMethods(Method->getParent(), Method)) {
7515 // If the function was marked as "static", we have a problem.
7516 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007517 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007518 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007519 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007520 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007521
7522 if (Method->isStatic())
7523 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007524 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007525
7526 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7527 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007528 CheckOverloadedOperatorDeclaration(NewFD)) {
7529 NewFD->setInvalidDecl();
7530 return Redeclaration;
7531 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007532
7533 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7534 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007535 CheckLiteralOperatorDeclaration(NewFD)) {
7536 NewFD->setInvalidDecl();
7537 return Redeclaration;
7538 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007539
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007540 // In C++, check default arguments now that we have merged decls. Unless
7541 // the lexical context is the class, because in this case this is done
7542 // during delayed parsing anyway.
7543 if (!CurContext->isRecord())
7544 CheckCXXDefaultArguments(NewFD);
Douglas Gregorb68e3992010-12-21 19:47:46 +00007545
7546 // If this function declares a builtin function, check the type of this
7547 // declaration against the expected type for the builtin.
7548 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7549 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007550 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007551 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7552 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7553 // The type of this function differs from the type of the builtin,
7554 // so forget about the builtin entirely.
7555 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7556 }
7557 }
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007558
7559 // If this function is declared as being extern "C", then check to see if
7560 // the function returns a UDT (class, struct, or union type) that is not C
7561 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007562 // But, issue any diagnostic on the first declaration only.
7563 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007564 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007565 if (R->isIncompleteType() && !R->isVoidType())
7566 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7567 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007568 else if (!R.isPODType(Context) && !R->isVoidType() &&
7569 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007570 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007571 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007572 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007573 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007574}
7575
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007576static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7577 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7578 if (!TSI)
7579 return SourceRange();
7580
7581 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007582 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007583 if (!FunctionTL)
7584 return SourceRange();
7585
David Blaikie39e6ab42013-02-18 22:06:02 +00007586 TypeLoc ResultTL = FunctionTL.getResultLoc();
7587 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007588 return ResultTL.getSourceRange();
7589
7590 return SourceRange();
7591}
7592
David Blaikie14068e82011-09-08 06:33:04 +00007593void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007594 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7595 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007596 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7597 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007598 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007599 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007600 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007601 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007602 ? diag::err_static_main : diag::warn_static_main)
7603 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7604 if (FD->isInlineSpecified())
7605 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7606 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007607 if (DS.isNoreturnSpecified()) {
7608 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7609 SourceRange NoreturnRange(NoreturnLoc,
7610 PP.getLocForEndOfToken(NoreturnLoc));
7611 Diag(NoreturnLoc, diag::ext_noreturn_main);
7612 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7613 << FixItHint::CreateRemoval(NoreturnRange);
7614 }
Richard Smitha5065862012-02-04 06:10:17 +00007615 if (FD->isConstexpr()) {
7616 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7617 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7618 FD->setConstexpr(false);
7619 }
John McCall13591ed2009-07-25 04:36:53 +00007620
7621 QualType T = FD->getType();
7622 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007623 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007624
John McCall75d8ba32012-02-14 19:50:52 +00007625 // All the standards say that main() should should return 'int'.
7626 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7627 // In C and C++, main magically returns 0 if you fall off the end;
7628 // set the flag which tells us that.
7629 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7630 FD->setHasImplicitReturnZero(true);
7631
7632 // In C with GNU extensions we allow main() to have non-integer return
7633 // type, but we should warn about the extension, and we disable the
7634 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007635 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007636 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7637
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007638 SourceRange ResultRange = getResultSourceRange(FD);
7639 if (ResultRange.isValid())
7640 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7641 << FixItHint::CreateReplacement(ResultRange, "int");
7642
John McCall75d8ba32012-02-14 19:50:52 +00007643 // Otherwise, this is just a flat-out error.
7644 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007645 SourceRange ResultRange = getResultSourceRange(FD);
7646 if (ResultRange.isValid())
7647 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7648 << FixItHint::CreateReplacement(ResultRange, "int");
7649 else
7650 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7651
John McCall13591ed2009-07-25 04:36:53 +00007652 FD->setInvalidDecl(true);
7653 }
7654
7655 // Treat protoless main() as nullary.
7656 if (isa<FunctionNoProtoType>(FT)) return;
7657
7658 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7659 unsigned nparams = FTP->getNumArgs();
7660 assert(FD->getNumParams() == nparams);
7661
John McCall66755862009-12-24 09:58:38 +00007662 bool HasExtraParameters = (nparams > 3);
7663
7664 // Darwin passes an undocumented fourth argument of type char**. If
7665 // other platforms start sprouting these, the logic below will start
7666 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007667 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007668 HasExtraParameters = false;
7669
7670 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007671 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7672 FD->setInvalidDecl(true);
7673 nparams = 3;
7674 }
7675
7676 // FIXME: a lot of the following diagnostics would be improved
7677 // if we had some location information about types.
7678
7679 QualType CharPP =
7680 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007681 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007682
7683 for (unsigned i = 0; i < nparams; ++i) {
7684 QualType AT = FTP->getArgType(i);
7685
7686 bool mismatch = true;
7687
7688 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7689 mismatch = false;
7690 else if (Expected[i] == CharPP) {
7691 // As an extension, the following forms are okay:
7692 // char const **
7693 // char const * const *
7694 // char * const *
7695
John McCall0953e762009-09-24 19:53:00 +00007696 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007697 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007698 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7699 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007700 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7701 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007702 qs.removeConst();
7703 mismatch = !qs.empty();
7704 }
7705 }
7706
7707 if (mismatch) {
7708 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7709 // TODO: suggest replacing given type with expected type
7710 FD->setInvalidDecl(true);
7711 }
7712 }
7713
7714 if (nparams == 1 && !FD->isInvalidDecl()) {
7715 Diag(FD->getLocation(), diag::warn_main_one_arg);
7716 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007717
7718 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007719 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7720 FD->setInvalidDecl();
7721 }
7722}
7723
7724void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7725 QualType T = FD->getType();
7726 assert(T->isFunctionType() && "function decl is not of function type");
7727 const FunctionType *FT = T->castAs<FunctionType>();
7728
7729 // Set an implicit return of 'zero' if the function can return some integral,
7730 // enumeration, pointer or nullptr type.
7731 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7732 FT->getResultType()->isAnyPointerType() ||
7733 FT->getResultType()->isNullPtrType())
7734 // DllMain is exempt because a return value of zero means it failed.
7735 if (FD->getName() != "DllMain")
7736 FD->setHasImplicitReturnZero(true);
7737
7738 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7739 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007740 FD->setInvalidDecl();
7741 }
John McCall8c4859a2009-07-24 03:03:21 +00007742}
7743
Eli Friedmanc594b322008-05-20 13:48:25 +00007744bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007745 // FIXME: Need strict checking. In C89, we need to check for
7746 // any assignment, increment, decrement, function-calls, or
7747 // commas outside of a sizeof. In C99, it's the same list,
7748 // except that the aforementioned are allowed in unevaluated
7749 // expressions. Everything else falls under the
7750 // "may accept other forms of constant expressions" exception.
7751 // (We never end up here for C++, so the constant expression
7752 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007753 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007754 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007755 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7756 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007757 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007758}
7759
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007760namespace {
7761 // Visits an initialization expression to see if OrigDecl is evaluated in
7762 // its own initialization and throws a warning if it does.
7763 class SelfReferenceChecker
7764 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7765 Sema &S;
7766 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007767 bool isRecordType;
7768 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007769 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007770
7771 public:
7772 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7773
7774 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007775 S(S), OrigDecl(OrigDecl) {
7776 isPODType = false;
7777 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007778 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007779 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7780 isPODType = VD->getType().isPODType(S.Context);
7781 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007782 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007783 }
7784 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007785
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007786 // For most expressions, the cast is directly above the DeclRefExpr.
7787 // For conditional operators, the cast can be outside the conditional
7788 // operator if both expressions are DeclRefExpr's.
7789 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007790 if (isReferenceType)
7791 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007792 E = E->IgnoreParenImpCasts();
7793 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7794 HandleDeclRefExpr(DRE);
7795 return;
7796 }
7797
7798 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7799 HandleValue(CO->getTrueExpr());
7800 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007801 return;
7802 }
7803
7804 if (isa<MemberExpr>(E)) {
7805 Expr *Base = E->IgnoreParenImpCasts();
7806 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7807 // Check for static member variables and don't warn on them.
7808 if (!isa<FieldDecl>(ME->getMemberDecl()))
7809 return;
7810 Base = ME->getBase()->IgnoreParenImpCasts();
7811 }
7812 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7813 HandleDeclRefExpr(DRE);
7814 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007815 }
7816 }
7817
Richard Trieu568f7852012-10-01 17:39:51 +00007818 // Reference types are handled here since all uses of references are
7819 // bad, not just r-value uses.
7820 void VisitDeclRefExpr(DeclRefExpr *E) {
7821 if (isReferenceType)
7822 HandleDeclRefExpr(E);
7823 }
7824
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007825 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007826 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007827 (isRecordType && E->getCastKind() == CK_NoOp))
7828 HandleValue(E->getSubExpr());
7829
7830 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007831 }
7832
Richard Trieu898267f2011-09-01 21:44:13 +00007833 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007834 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007835 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007836
Richard Trieu6b2cc422012-10-03 00:41:36 +00007837 // Warn when a non-static method call is followed by non-static member
7838 // field accesses, which is followed by a DeclRefExpr.
7839 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7840 bool Warn = (MD && !MD->isStatic());
7841 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7842 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7843 if (!isa<FieldDecl>(ME->getMemberDecl()))
7844 Warn = false;
7845 Base = ME->getBase()->IgnoreParenImpCasts();
7846 }
Richard Trieu898267f2011-09-01 21:44:13 +00007847
Richard Trieu6b2cc422012-10-03 00:41:36 +00007848 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7849 if (Warn)
7850 HandleDeclRefExpr(DRE);
7851 return;
7852 }
7853
7854 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7855 // Visit that expression.
7856 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007857 }
7858
Richard Trieu8af742a2013-03-26 03:41:40 +00007859 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7860 if (E->getNumArgs() > 0)
7861 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7862 HandleDeclRefExpr(DRE);
7863
7864 Inherited::VisitCXXOperatorCallExpr(E);
7865 }
7866
Richard Trieu898267f2011-09-01 21:44:13 +00007867 void VisitUnaryOperator(UnaryOperator *E) {
7868 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007869 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7870 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7871 if (!isPODType)
7872 HandleValue(E->getSubExpr());
7873 return;
7874 }
Richard Trieu898267f2011-09-01 21:44:13 +00007875 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007876 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007877
7878 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7879
Richard Trieu898267f2011-09-01 21:44:13 +00007880 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007881 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007882 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007883 unsigned diag;
7884 if (isReferenceType) {
7885 diag = diag::warn_uninit_self_reference_in_reference_init;
7886 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7887 diag = diag::warn_static_self_reference_in_init;
7888 } else {
7889 diag = diag::warn_uninit_self_reference_in_init;
7890 }
7891
Richard Trieu898267f2011-09-01 21:44:13 +00007892 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007893 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007894 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007895 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007896 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007897 }
7898 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007899
Richard Trieu568f7852012-10-01 17:39:51 +00007900 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7901 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7902 bool DirectInit) {
7903 // Parameters arguments are occassionially constructed with itself,
7904 // for instance, in recursive functions. Skip them.
7905 if (isa<ParmVarDecl>(OrigDecl))
7906 return;
7907
7908 E = E->IgnoreParens();
7909
7910 // Skip checking T a = a where T is not a record or reference type.
7911 // Doing so is a way to silence uninitialized warnings.
7912 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7913 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7914 if (ICE->getCastKind() == CK_LValueToRValue)
7915 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7916 if (DRE->getDecl() == OrigDecl)
7917 return;
7918
7919 SelfReferenceChecker(S, OrigDecl).Visit(E);
7920 }
Richard Trieu898267f2011-09-01 21:44:13 +00007921}
7922
Douglas Gregor09f41cf2009-01-14 15:45:31 +00007923/// AddInitializerToDecl - Adds the initializer Init to the
7924/// declaration dcl. If DirectInit is true, this is C++ direct
7925/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00007926void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
7927 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00007928 // If there is no declaration, there was an error parsing it. Just ignore
7929 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00007930 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00007931 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007932
Douglas Gregor021c3b32009-03-11 23:00:04 +00007933 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
7934 // With declarators parsed the way they are, the parser cannot
7935 // distinguish between a normal initializer and a pure-specifier.
7936 // Thus this grotesque test.
7937 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00007938 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00007939 Context.getCanonicalType(IL->getType()) == Context.IntTy)
7940 CheckPureMethod(Method, Init->getSourceRange());
7941 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00007942 Diag(Method->getLocation(), diag::err_member_function_initialization)
7943 << Method->getDeclName() << Init->getSourceRange();
7944 Method->setInvalidDecl();
7945 }
7946 return;
7947 }
7948
Steve Naroff410e3e22007-09-12 20:13:48 +00007949 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7950 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00007951 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
7952 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00007953 RealDecl->setInvalidDecl();
7954 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007955 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00007956 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
7957
Richard Smith01888722011-12-15 19:20:59 +00007958 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00007959 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00007960 Expr *DeduceInit = Init;
7961 // Initializer could be a C++ direct-initializer. Deduction only works if it
7962 // contains exactly one expression.
7963 if (CXXDirectInit) {
7964 if (CXXDirectInit->getNumExprs() == 0) {
7965 // It isn't possible to write this directly, but it is possible to
7966 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00007967 Diag(CXXDirectInit->getLocStart(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00007968 diag::err_auto_var_init_no_expression)
7969 << VDecl->getDeclName() << VDecl->getType()
7970 << VDecl->getSourceRange();
7971 RealDecl->setInvalidDecl();
7972 return;
7973 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00007974 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00007975 diag::err_auto_var_init_multiple_expressions)
7976 << VDecl->getDeclName() << VDecl->getType()
7977 << VDecl->getSourceRange();
7978 RealDecl->setInvalidDecl();
7979 return;
7980 } else {
7981 DeduceInit = CXXDirectInit->getExpr(0);
7982 }
7983 }
Douglas Gregor1344e942013-03-07 22:57:58 +00007984
7985 // Expressions default to 'id' when we're in a debugger.
7986 bool DefaultedToAuto = false;
7987 if (getLangOpts().DebuggerCastResultToId &&
7988 Init->getType() == Context.UnknownAnyTy) {
7989 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
7990 if (Result.isInvalid()) {
7991 VDecl->setInvalidDecl();
7992 return;
7993 }
7994 Init = Result.take();
7995 DefaultedToAuto = true;
7996 }
Richard Smith9b131752013-04-30 21:23:01 +00007997
7998 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00007999 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008000 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008001 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008002 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008003 RealDecl->setInvalidDecl();
8004 return;
8005 }
Richard Smith9b131752013-04-30 21:23:01 +00008006 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008007 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008008
John McCallf85e1932011-06-15 23:02:42 +00008009 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008010 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008011 VDecl->setInvalidDecl();
8012
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008013 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8014 // 'id' instead of a specific object type prevents most of our usual checks.
8015 // We only want to warn outside of template instantiations, though:
8016 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008017 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008018 DeducedType->isObjCIdType()) {
8019 SourceLocation Loc =
8020 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008021 Diag(Loc, diag::warn_auto_var_is_id)
8022 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8023 }
8024
Richard Smith34b41d92011-02-20 03:19:35 +00008025 // If this is a redeclaration, check that the type we just deduced matches
8026 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008027 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8028 // We never need to merge the type, because we cannot form an incomplete
8029 // array of auto, nor deduce such a type.
8030 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8031 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008032
8033 // Check the deduced type is valid for a variable declaration.
8034 CheckVariableDeclarationType(VDecl);
8035 if (VDecl->isInvalidDecl())
8036 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008037 }
Richard Smith01888722011-12-15 19:20:59 +00008038
8039 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8040 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8041 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8042 VDecl->setInvalidDecl();
8043 return;
8044 }
8045
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008046 if (!VDecl->getType()->isDependentType()) {
8047 // A definition must end up with a complete type, which means it must be
8048 // complete with the restriction that an array type might be completed by
8049 // the initializer; note that later code assumes this restriction.
8050 QualType BaseDeclType = VDecl->getType();
8051 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8052 BaseDeclType = Array->getElementType();
8053 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8054 diag::err_typecheck_decl_incomplete_type)) {
8055 RealDecl->setInvalidDecl();
8056 return;
8057 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008058
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008059 // The variable can not have an abstract class type.
8060 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8061 diag::err_abstract_type_in_decl,
8062 AbstractVariableType))
8063 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008064 }
8065
Sebastian Redl31310a22010-02-01 20:16:42 +00008066 const VarDecl *Def;
8067 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008068 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008069 << VDecl->getDeclName();
8070 Diag(Def->getLocation(), diag::note_previous_definition);
8071 VDecl->setInvalidDecl();
8072 return;
8073 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008074
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008075 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008076 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008077 // C++ [class.static.data]p4
8078 // If a static data member is of const integral or const
8079 // enumeration type, its declaration in the class definition can
8080 // specify a constant-initializer which shall be an integral
8081 // constant expression (5.19). In that case, the member can appear
8082 // in integral constant expressions. The member shall still be
8083 // defined in a namespace scope if it is used in the program and the
8084 // namespace scope definition shall not contain an initializer.
8085 //
8086 // We already performed a redefinition check above, but for static
8087 // data members we also need to check whether there was an in-class
8088 // declaration with an initializer.
8089 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008090 Diag(VDecl->getLocation(), diag::err_redefinition)
8091 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008092 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8093 return;
8094 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008095
Douglas Gregora31040f2010-12-16 01:31:22 +00008096 if (VDecl->hasLocalStorage())
8097 getCurFunction()->setHasBranchProtectedScope();
8098
8099 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8100 VDecl->setInvalidDecl();
8101 return;
8102 }
8103 }
John McCalle46f62c2010-08-01 01:24:59 +00008104
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008105 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8106 // a kernel function cannot be initialized."
8107 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8108 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8109 VDecl->setInvalidDecl();
8110 return;
8111 }
8112
Steve Naroffbb204692007-09-12 14:07:44 +00008113 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008114 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008115 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008116
Douglas Gregor1344e942013-03-07 22:57:58 +00008117 // Expressions default to 'id' when we're in a debugger
8118 // and we are assigning it to a variable of Objective-C pointer type.
8119 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8120 Init->getType() == Context.UnknownAnyTy) {
8121 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8122 if (Result.isInvalid()) {
8123 VDecl->setInvalidDecl();
8124 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008125 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008126 Init = Result.take();
8127 }
Richard Smith01888722011-12-15 19:20:59 +00008128
8129 // Perform the initialization.
8130 if (!VDecl->isInvalidDecl()) {
8131 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8132 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008133 = DirectInit ?
8134 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8135 Init->getLocStart(),
8136 Init->getLocEnd())
8137 : InitializationKind::CreateDirectList(
8138 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008139 : InitializationKind::CreateCopy(VDecl->getLocation(),
8140 Init->getLocStart());
8141
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008142 MultiExprArg Args = Init;
8143 if (CXXDirectInit)
8144 Args = MultiExprArg(CXXDirectInit->getExprs(),
8145 CXXDirectInit->getNumExprs());
8146
8147 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8148 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008149 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008150 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008151 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008152 }
Richard Smith01888722011-12-15 19:20:59 +00008153
8154 Init = Result.takeAs<Expr>();
8155 }
8156
Richard Trieu568f7852012-10-01 17:39:51 +00008157 // Check for self-references within variable initializers.
8158 // Variables declared within a function/method body (except for references)
8159 // are handled by a dataflow analysis.
8160 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8161 VDecl->getType()->isReferenceType()) {
8162 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8163 }
8164
Richard Smith01888722011-12-15 19:20:59 +00008165 // If the type changed, it means we had an incomplete type that was
8166 // completed by the initializer. For example:
8167 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008168 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008169 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008170 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008171
Jordan Rosee10f4d32012-09-15 02:48:31 +00008172 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008173 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8174
Jordan Rosee10f4d32012-09-15 02:48:31 +00008175 if (VDecl->hasAttr<BlocksAttr>())
8176 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008177
8178 // It is safe to assign a weak reference into a strong variable.
8179 // Although this code can still have problems:
8180 // id x = self.weakProp;
8181 // id y = self.weakProp;
8182 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8183 // paths through the function. This should be revisited if
8184 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008185 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008186 DiagnosticsEngine::Level Level =
8187 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8188 Init->getLocStart());
8189 if (Level != DiagnosticsEngine::Ignored)
8190 getCurFunction()->markSafeWeakUse(Init);
8191 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008192 }
8193
Richard Smith41956372013-01-14 22:39:08 +00008194 // The initialization is usually a full-expression.
8195 //
8196 // FIXME: If this is a braced initialization of an aggregate, it is not
8197 // an expression, and each individual field initializer is a separate
8198 // full-expression. For instance, in:
8199 //
8200 // struct Temp { ~Temp(); };
8201 // struct S { S(Temp); };
8202 // struct T { S a, b; } t = { Temp(), Temp() }
8203 //
8204 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008205 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8206 false,
8207 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008208 if (Result.isInvalid()) {
8209 VDecl->setInvalidDecl();
8210 return;
8211 }
8212 Init = Result.take();
8213
Richard Smith01888722011-12-15 19:20:59 +00008214 // Attach the initializer to the decl.
8215 VDecl->setInit(Init);
8216
8217 if (VDecl->isLocalVarDecl()) {
8218 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8219 // static storage duration shall be constant expressions or string literals.
8220 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008221 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8222 if (VDecl->getStorageClass() == SC_Static)
8223 CheckForConstantInitializer(Init, DclT);
8224 // C89 is stricter than C99 for non-static aggregate types.
8225 // C89 6.5.7p3: All the expressions [...] in an initializer list
8226 // for an object that has aggregate or union type shall be
8227 // constant expressions.
8228 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008229 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008230 !Init->isConstantInitializer(Context, false))
8231 Diag(Init->getExprLoc(),
8232 diag::ext_aggregate_init_not_constant)
8233 << Init->getSourceRange();
8234 }
Mike Stump1eb44332009-09-09 15:08:12 +00008235 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008236 VDecl->getLexicalDeclContext()->isRecord()) {
8237 // This is an in-class initialization for a static data member, e.g.,
8238 //
8239 // struct S {
8240 // static const int value = 17;
8241 // };
8242
Douglas Gregor021c3b32009-03-11 23:00:04 +00008243 // C++ [class.mem]p4:
8244 // A member-declarator can contain a constant-initializer only
8245 // if it declares a static member (9.4) of const integral or
8246 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008247 //
Richard Smith01888722011-12-15 19:20:59 +00008248 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008249 // If a non-volatile const static data member is of integral or
8250 // enumeration type, its declaration in the class definition can
8251 // specify a brace-or-equal-initializer in which every initalizer-clause
8252 // that is an assignment-expression is a constant expression. A static
8253 // data member of literal type can be declared in the class definition
8254 // with the constexpr specifier; if so, its declaration shall specify a
8255 // brace-or-equal-initializer in which every initializer-clause that is
8256 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008257
8258 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008259 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008260
Richard Smithc6d990a2011-09-29 19:11:37 +00008261 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008262 // type. We separately check that every constexpr variable is of literal
8263 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008264 } else if (VDecl->isConstexpr()) {
8265
John McCall4e635642010-09-10 23:21:22 +00008266 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008267 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008268 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8269 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008270 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008271
8272 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008273 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008274 // Check whether the expression is a constant expression.
8275 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008276 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008277 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008278 // in-class initializer cannot be volatile.
8279 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8280 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008281 ; // Nothing to check.
8282 else if (Init->isIntegerConstantExpr(Context, &Loc))
8283 ; // Ok, it's an ICE!
8284 else if (Init->isEvaluatable(Context)) {
8285 // If we can constant fold the initializer through heroics, accept it,
8286 // but report this as a use of an extension for -pedantic.
8287 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8288 << Init->getSourceRange();
8289 } else {
8290 // Otherwise, this is some crazy unknown case. Report the issue at the
8291 // location provided by the isIntegerConstantExpr failed check.
8292 Diag(Loc, diag::err_in_class_initializer_non_constant)
8293 << Init->getSourceRange();
8294 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008295 }
8296
Richard Smith01888722011-12-15 19:20:59 +00008297 // We allow foldable floating-point constants as an extension.
8298 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008299 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8300 // it anyway and provide a fixit to add the 'constexpr'.
8301 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008302 Diag(VDecl->getLocation(),
8303 diag::ext_in_class_initializer_float_type_cxx11)
8304 << DclT << Init->getSourceRange();
8305 Diag(VDecl->getLocStart(),
8306 diag::note_in_class_initializer_float_type_cxx11)
8307 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008308 } else {
8309 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8310 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008311
Richard Smithb4b1d692013-01-25 04:22:16 +00008312 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8313 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8314 << Init->getSourceRange();
8315 VDecl->setInvalidDecl();
8316 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008317 }
Richard Smith947be192011-09-29 23:18:34 +00008318
Richard Smith01888722011-12-15 19:20:59 +00008319 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008320 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008321 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008322 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008323 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8324 VDecl->setConstexpr(true);
8325
Richard Smithc6d990a2011-09-29 19:11:37 +00008326 } else {
8327 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008328 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008329 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008330 }
Steve Naroff248a7532008-04-15 22:42:06 +00008331 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008332 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008333 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008334 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8335 VDecl->isExternC())))
Steve Naroff410e3e22007-09-12 20:13:48 +00008336 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008337
Richard Smith01888722011-12-15 19:20:59 +00008338 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008339 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008340 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008341 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8342 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8343 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008344 !Init->isConstantInitializer(
8345 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008346 // GNU C++98 edits for __thread, [basic.start.init]p4:
8347 // An object of thread storage duration shall not require dynamic
8348 // initialization.
8349 // FIXME: Need strict checking here.
8350 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8351 if (getLangOpts().CPlusPlus11)
8352 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8353 }
Steve Naroffbb204692007-09-12 14:07:44 +00008354 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008355
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008356 // We will represent direct-initialization similarly to copy-initialization:
8357 // int x(1); -as-> int x = 1;
8358 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8359 //
8360 // Clients that want to distinguish between the two forms, can check for
8361 // direct initializer using VarDecl::getInitStyle().
8362 // A major benefit is that clients that don't particularly care about which
8363 // exactly form was it (like the CodeGen) can handle both cases without
8364 // special case code.
8365
8366 // C++ 8.5p11:
8367 // The form of initialization (using parentheses or '=') is generally
8368 // insignificant, but does matter when the entity being initialized has a
8369 // class type.
8370 if (CXXDirectInit) {
8371 assert(DirectInit && "Call-style initializer must be direct init.");
8372 VDecl->setInitStyle(VarDecl::CallInit);
8373 } else if (DirectInit) {
8374 // This must be list-initialization. No other way is direct-initialization.
8375 VDecl->setInitStyle(VarDecl::ListInit);
8376 }
8377
John McCall2998d6b2011-01-19 11:48:09 +00008378 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008379}
8380
John McCall7727acf2010-03-31 02:13:20 +00008381/// ActOnInitializerError - Given that there was an error parsing an
8382/// initializer for the given declaration, try to return to some form
8383/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008384void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008385 // Our main concern here is re-establishing invariants like "a
8386 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008387 if (!D || D->isInvalidDecl()) return;
8388
8389 VarDecl *VD = dyn_cast<VarDecl>(D);
8390 if (!VD) return;
8391
Richard Smith34b41d92011-02-20 03:19:35 +00008392 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008393 if (ParsingInitForAutoVars.count(D)) {
8394 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008395 return;
8396 }
8397
John McCall7727acf2010-03-31 02:13:20 +00008398 QualType Ty = VD->getType();
8399 if (Ty->isDependentType()) return;
8400
8401 // Require a complete type.
8402 if (RequireCompleteType(VD->getLocation(),
8403 Context.getBaseElementType(Ty),
8404 diag::err_typecheck_decl_incomplete_type)) {
8405 VD->setInvalidDecl();
8406 return;
8407 }
8408
8409 // Require an abstract type.
8410 if (RequireNonAbstractType(VD->getLocation(), Ty,
8411 diag::err_abstract_type_in_decl,
8412 AbstractVariableType)) {
8413 VD->setInvalidDecl();
8414 return;
8415 }
8416
8417 // Don't bother complaining about constructors or destructors,
8418 // though.
8419}
8420
John McCalld226f652010-08-21 09:40:31 +00008421void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008422 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008423 // If there is no declaration, there was an error parsing it. Just ignore it.
8424 if (RealDecl == 0)
8425 return;
8426
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008427 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8428 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008429
Richard Smithdd4b3502011-12-25 21:17:58 +00008430 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008431 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008432 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8433 << Var->getDeclName() << Type;
8434 Var->setInvalidDecl();
8435 return;
8436 }
Mike Stump1eb44332009-09-09 15:08:12 +00008437
Richard Smithdd4b3502011-12-25 21:17:58 +00008438 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008439 // the constexpr specifier; if so, its declaration shall specify
8440 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008441 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8442 // the definition of a variable [...] or the declaration of a static data
8443 // member.
8444 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8445 if (Var->isStaticDataMember())
8446 Diag(Var->getLocation(),
8447 diag::err_constexpr_static_mem_var_requires_init)
8448 << Var->getDeclName();
8449 else
8450 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008451 Var->setInvalidDecl();
8452 return;
8453 }
8454
Douglas Gregor60c93c92010-02-09 07:26:29 +00008455 switch (Var->isThisDeclarationADefinition()) {
8456 case VarDecl::Definition:
8457 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8458 break;
8459
8460 // We have an out-of-line definition of a static data member
8461 // that has an in-class initializer, so we type-check this like
8462 // a declaration.
8463 //
8464 // Fall through
8465
8466 case VarDecl::DeclarationOnly:
8467 // It's only a declaration.
8468
8469 // Block scope. C99 6.7p7: If an identifier for an object is
8470 // declared with no linkage (C99 6.2.2p6), the type for the
8471 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008472 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008473 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008474 RequireCompleteType(Var->getLocation(), Type,
8475 diag::err_typecheck_decl_incomplete_type))
8476 Var->setInvalidDecl();
8477
8478 // Make sure that the type is not abstract.
8479 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8480 RequireNonAbstractType(Var->getLocation(), Type,
8481 diag::err_abstract_type_in_decl,
8482 AbstractVariableType))
8483 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008484 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008485 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008486 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008487 Diag(Var->getLocation(), diag::note_private_extern);
8488 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008489
Douglas Gregor60c93c92010-02-09 07:26:29 +00008490 return;
8491
8492 case VarDecl::TentativeDefinition:
8493 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8494 // object that has file scope without an initializer, and without a
8495 // storage-class specifier or with the storage-class specifier "static",
8496 // constitutes a tentative definition. Note: A tentative definition with
8497 // external linkage is valid (C99 6.2.2p5).
8498 if (!Var->isInvalidDecl()) {
8499 if (const IncompleteArrayType *ArrayT
8500 = Context.getAsIncompleteArrayType(Type)) {
8501 if (RequireCompleteType(Var->getLocation(),
8502 ArrayT->getElementType(),
8503 diag::err_illegal_decl_array_incomplete_type))
8504 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008505 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008506 // C99 6.9.2p3: If the declaration of an identifier for an object is
8507 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8508 // declared type shall not be an incomplete type.
8509 // NOTE: code such as the following
8510 // static struct s;
8511 // struct s { int a; };
8512 // is accepted by gcc. Hence here we issue a warning instead of
8513 // an error and we do not invalidate the static declaration.
8514 // NOTE: to avoid multiple warnings, only check the first declaration.
Douglas Gregoref96ee02012-01-14 16:38:05 +00008515 if (Var->getPreviousDecl() == 0)
Douglas Gregor60c93c92010-02-09 07:26:29 +00008516 RequireCompleteType(Var->getLocation(), Type,
8517 diag::ext_typecheck_decl_incomplete_type);
8518 }
8519 }
8520
8521 // Record the tentative definition; we're done.
8522 if (!Var->isInvalidDecl())
8523 TentativeDefinitions.push_back(Var);
8524 return;
8525 }
8526
8527 // Provide a specific diagnostic for uninitialized variable
8528 // definitions with incomplete array type.
8529 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008530 Diag(Var->getLocation(),
8531 diag::err_typecheck_incomplete_array_needs_initializer);
8532 Var->setInvalidDecl();
8533 return;
8534 }
8535
John McCallb567a8b2010-08-01 01:25:24 +00008536 // Provide a specific diagnostic for uninitialized variable
8537 // definitions with reference type.
8538 if (Type->isReferenceType()) {
8539 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8540 << Var->getDeclName()
8541 << SourceRange(Var->getLocation(), Var->getLocation());
8542 Var->setInvalidDecl();
8543 return;
8544 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008545
8546 // Do not attempt to type-check the default initializer for a
8547 // variable with dependent type.
8548 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008549 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008550
Douglas Gregor60c93c92010-02-09 07:26:29 +00008551 if (Var->isInvalidDecl())
8552 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008553
Douglas Gregor60c93c92010-02-09 07:26:29 +00008554 if (RequireCompleteType(Var->getLocation(),
8555 Context.getBaseElementType(Type),
8556 diag::err_typecheck_decl_incomplete_type)) {
8557 Var->setInvalidDecl();
8558 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008559 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008560
Douglas Gregor60c93c92010-02-09 07:26:29 +00008561 // The variable can not have an abstract class type.
8562 if (RequireNonAbstractType(Var->getLocation(), Type,
8563 diag::err_abstract_type_in_decl,
8564 AbstractVariableType)) {
8565 Var->setInvalidDecl();
8566 return;
8567 }
8568
Douglas Gregor4337dc72011-05-21 17:52:48 +00008569 // Check for jumps past the implicit initializer. C++0x
8570 // clarifies that this applies to a "variable with automatic
8571 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008572 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008573 // A program that jumps from a point where a variable with automatic
8574 // storage duration is not in scope to a point where it is in scope is
8575 // ill-formed unless the variable has scalar type, class type with a
8576 // trivial default constructor and a trivial destructor, a cv-qualified
8577 // version of one of these types, or an array of one of the preceding
8578 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008579 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008580 if (const RecordType *Record
8581 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008582 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008583 // Mark the function for further checking even if the looser rules of
8584 // C++11 do not require such checks, so that we can diagnose
8585 // incompatibilities with C++98.
8586 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008587 getCurFunction()->setHasBranchProtectedScope();
8588 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008589 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008590
8591 // C++03 [dcl.init]p9:
8592 // If no initializer is specified for an object, and the
8593 // object is of (possibly cv-qualified) non-POD class type (or
8594 // array thereof), the object shall be default-initialized; if
8595 // the object is of const-qualified type, the underlying class
8596 // type shall have a user-declared default
8597 // constructor. Otherwise, if no initializer is specified for
8598 // a non- static object, the object and its subobjects, if
8599 // any, have an indeterminate initial value); if the object
8600 // or any of its subobjects are of const-qualified type, the
8601 // program is ill-formed.
8602 // C++0x [dcl.init]p11:
8603 // If no initializer is specified for an object, the object is
8604 // default-initialized; [...].
8605 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8606 InitializationKind Kind
8607 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008608
8609 InitializationSequence InitSeq(*this, Entity, Kind, None);
8610 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008611 if (Init.isInvalid())
8612 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008613 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008614 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008615 // This is important for template substitution.
8616 Var->setInitStyle(VarDecl::CallInit);
8617 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008618
John McCall2998d6b2011-01-19 11:48:09 +00008619 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008620 }
8621}
8622
Richard Smithad762fc2011-04-14 22:09:26 +00008623void Sema::ActOnCXXForRangeDecl(Decl *D) {
8624 VarDecl *VD = dyn_cast<VarDecl>(D);
8625 if (!VD) {
8626 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8627 D->setInvalidDecl();
8628 return;
8629 }
8630
8631 VD->setCXXForRangeDecl(true);
8632
8633 // for-range-declaration cannot be given a storage class specifier.
8634 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008635 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008636 case SC_None:
8637 break;
8638 case SC_Extern:
8639 Error = 0;
8640 break;
8641 case SC_Static:
8642 Error = 1;
8643 break;
8644 case SC_PrivateExtern:
8645 Error = 2;
8646 break;
8647 case SC_Auto:
8648 Error = 3;
8649 break;
8650 case SC_Register:
8651 Error = 4;
8652 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008653 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008654 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008655 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008656 if (VD->isConstexpr())
8657 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008658 if (Error != -1) {
8659 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8660 << VD->getDeclName() << Error;
8661 D->setInvalidDecl();
8662 }
8663}
8664
John McCall2998d6b2011-01-19 11:48:09 +00008665void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8666 if (var->isInvalidDecl()) return;
8667
John McCallf85e1932011-06-15 23:02:42 +00008668 // In ARC, don't allow jumps past the implicit initialization of a
8669 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008670 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008671 var->hasLocalStorage()) {
8672 switch (var->getType().getObjCLifetime()) {
8673 case Qualifiers::OCL_None:
8674 case Qualifiers::OCL_ExplicitNone:
8675 case Qualifiers::OCL_Autoreleasing:
8676 break;
8677
8678 case Qualifiers::OCL_Weak:
8679 case Qualifiers::OCL_Strong:
8680 getCurFunction()->setHasBranchProtectedScope();
8681 break;
8682 }
8683 }
8684
Eli Friedmane4851f22012-10-23 20:19:32 +00008685 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008686 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008687 getDiagnostics().getDiagnosticLevel(
8688 diag::warn_missing_variable_declarations,
8689 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008690 // Find a previous declaration that's not a definition.
8691 VarDecl *prev = var->getPreviousDecl();
8692 while (prev && prev->isThisDeclarationADefinition())
8693 prev = prev->getPreviousDecl();
8694
8695 if (!prev)
8696 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8697 }
8698
Richard Smith6a570f62013-04-14 20:11:31 +00008699 if (var->getTLSKind() == VarDecl::TLS_Static &&
8700 var->getType().isDestructedType()) {
8701 // GNU C++98 edits for __thread, [basic.start.term]p3:
8702 // The type of an object with thread storage duration shall not
8703 // have a non-trivial destructor.
8704 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8705 if (getLangOpts().CPlusPlus11)
8706 Diag(var->getLocation(), diag::note_use_thread_local);
8707 }
8708
John McCall2998d6b2011-01-19 11:48:09 +00008709 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008710 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008711
Richard Smitha67d5032012-11-09 23:03:14 +00008712 QualType type = var->getType();
8713 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008714
8715 // __block variables might require us to capture a copy-initializer.
8716 if (var->hasAttr<BlocksAttr>()) {
8717 // It's currently invalid to ever have a __block variable with an
8718 // array type; should we diagnose that here?
8719
8720 // Regardless, we don't want to ignore array nesting when
8721 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008722 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008723 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008724 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008725 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008726 ExprResult result
8727 = PerformMoveOrCopyInitialization(
8728 InitializedEntity::InitializeBlock(poi, type, false),
8729 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008730 if (!result.isInvalid()) {
8731 result = MaybeCreateExprWithCleanups(result);
8732 Expr *init = result.takeAs<Expr>();
8733 Context.setBlockVarCopyInits(var, init);
8734 }
8735 }
8736 }
8737
Richard Smith66f85712011-11-07 22:16:17 +00008738 Expr *Init = var->getInit();
8739 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008740 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008741
Richard Smith9568f0c2012-10-29 18:26:47 +00008742 if (!var->getDeclContext()->isDependentContext() &&
8743 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008744 if (IsGlobal && !var->isConstexpr() &&
8745 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8746 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008747 != DiagnosticsEngine::Ignored) {
8748 // Warn about globals which don't have a constant initializer. Don't
8749 // warn about globals with a non-trivial destructor because we already
8750 // warned about them.
8751 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8752 if (!(RD && !RD->hasTrivialDestructor()) &&
8753 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8754 Diag(var->getLocation(), diag::warn_global_constructor)
8755 << Init->getSourceRange();
8756 }
Richard Smith099e7f62011-12-19 06:19:21 +00008757
Richard Smith099e7f62011-12-19 06:19:21 +00008758 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008759 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008760 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8761 SourceLocation DiagLoc = var->getLocation();
8762 // If the note doesn't add any useful information other than a source
8763 // location, fold it into the primary diagnostic.
8764 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8765 diag::note_invalid_subexpr_in_const_expr) {
8766 DiagLoc = Notes[0].first;
8767 Notes.clear();
8768 }
8769 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8770 << var << Init->getSourceRange();
8771 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8772 Diag(Notes[I].first, Notes[I].second);
8773 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008774 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008775 // Check whether the initializer of a const variable of integral or
8776 // enumeration type is an ICE now, since we can't tell whether it was
8777 // initialized by a constant expression if we check later.
8778 var->checkInitIsICE();
8779 }
Richard Smith66f85712011-11-07 22:16:17 +00008780 }
John McCall2998d6b2011-01-19 11:48:09 +00008781
8782 // Require the destructor.
8783 if (const RecordType *recordType = baseType->getAs<RecordType>())
8784 FinalizeVarWithDestructor(var, recordType);
8785}
8786
Richard Smith483b9f32011-02-21 20:05:19 +00008787/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8788/// any semantic actions necessary after any initializer has been attached.
8789void
8790Sema::FinalizeDeclaration(Decl *ThisDecl) {
8791 // Note that we are no longer parsing the initializer for this declaration.
8792 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008793
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008794 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008795 if (!VD)
8796 return;
8797
Rafael Espindola29535ba2013-08-16 23:18:50 +00008798 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8799 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8800 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8801 VD->dropAttr<UsedAttr>();
8802 }
8803 }
8804
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008805 const DeclContext *DC = VD->getDeclContext();
8806 // If there's a #pragma GCC visibility in scope, and this isn't a class
8807 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008808 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008809 AddPushedVisibilityAttribute(VD);
8810
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008811 if (VD->isFileVarDecl())
8812 MarkUnusedFileScopedDecl(VD);
8813
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008814 // Now we have parsed the initializer and can update the table of magic
8815 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008816 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8817 !VD->getType()->isIntegralOrEnumerationType())
8818 return;
8819
8820 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8821 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8822 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8823 I != E; ++I) {
8824 const Expr *MagicValueExpr = VD->getInit();
8825 if (!MagicValueExpr) {
8826 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008827 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008828 llvm::APSInt MagicValueInt;
8829 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8830 Diag(I->getRange().getBegin(),
8831 diag::err_type_tag_for_datatype_not_ice)
8832 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8833 continue;
8834 }
8835 if (MagicValueInt.getActiveBits() > 64) {
8836 Diag(I->getRange().getBegin(),
8837 diag::err_type_tag_for_datatype_too_large)
8838 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8839 continue;
8840 }
8841 uint64_t MagicValue = MagicValueInt.getZExtValue();
8842 RegisterTypeTagForDatatype(I->getArgumentKind(),
8843 MagicValue,
8844 I->getMatchingCType(),
8845 I->getLayoutCompatible(),
8846 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008847 }
Richard Smith483b9f32011-02-21 20:05:19 +00008848}
8849
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008850Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8851 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008852 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008853
8854 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008855 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008856
David Majnemeraa824612013-09-17 23:57:10 +00008857 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008858 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008859 if (Decl *D = Group[i]) {
8860 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8861 if (!FirstDeclaratorInGroup)
8862 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008863 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008864 }
Richard Smith406c38e2011-02-23 00:37:57 +00008865
Eli Friedman5e867c82013-07-10 00:30:46 +00008866 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008867 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008868 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008869 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8870 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8871 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008872 }
David Blaikie66cff722012-11-14 01:52:05 +00008873
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008874 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008875}
8876
8877/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8878/// group, performing any necessary semantic checking.
8879Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008880Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008881 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008882 // C++0x [dcl.spec.auto]p7:
8883 // If the type deduced for the template parameter U is not the same in each
8884 // deduction, the program is ill-formed.
8885 // FIXME: When initializer-list support is added, a distinction is needed
8886 // between the deduced type U and the deduced type which 'auto' stands for.
8887 // auto a = 0, b = { 1, 2, 3 };
8888 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008889 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008890 QualType Deduced;
8891 CanQualType DeducedCanon;
8892 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008893 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00008894 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8895 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00008896 // Don't reissue diagnostics when instantiating a template.
8897 if (AT && D->isInvalidDecl())
8898 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00008899 QualType U = AT ? AT->getDeducedType() : QualType();
8900 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008901 CanQualType UCanon = Context.getCanonicalType(U);
8902 if (Deduced.isNull()) {
8903 Deduced = U;
8904 DeducedCanon = UCanon;
8905 DeducedDecl = D;
8906 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00008907 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
8908 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00008909 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00008910 << Deduced << DeducedDecl->getDeclName()
8911 << U << D->getDeclName()
8912 << DeducedDecl->getInit()->getSourceRange()
8913 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00008914 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008915 break;
8916 }
8917 }
8918 }
8919 }
8920 }
8921
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008922 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008923
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008924 return DeclGroupPtrTy::make(
8925 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00008926}
Steve Naroffe1223f72007-08-28 03:03:08 +00008927
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008928void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008929 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008930}
8931
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008932void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008933 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008934 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008935 return;
8936
8937 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
8938 Group[0]->getLocation())
8939 == DiagnosticsEngine::Ignored)
8940 return;
8941
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008942 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008943 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008944 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008945 // additional declaration references:
8946 // 'typedef struct S {} S;'
8947 // 'typedef struct S *S;'
8948 // 'struct S *pS;'
8949 // FinalizeDeclaratorGroup adds these as separate declarations.
8950 Decl *MaybeTagDecl = Group[0];
8951 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008952 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008953 }
8954 }
8955
8956 // See if there are any new comments that are not attached to a decl.
8957 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
8958 if (!Comments.empty() &&
8959 !Comments.back()->isAttached()) {
8960 // There is at least one comment that not attached to a decl.
8961 // Maybe it should be attached to one of these decls?
8962 //
8963 // Note that this way we pick up not only comments that precede the
8964 // declaration, but also comments that *follow* the declaration -- thanks to
8965 // the lookahead in the lexer: we've consumed the semicolon and looked
8966 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008967 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00008968 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00008969 }
8970}
Chris Lattner682bf922009-03-29 16:50:03 +00008971
Chris Lattner04421082008-04-08 04:40:51 +00008972/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
8973/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00008974Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00008975 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00008976
Chris Lattner04421082008-04-08 04:40:51 +00008977 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00008978 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00008979 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00008980 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00008981 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00008982 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00008983 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
8984 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00008985 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00008986 Diag(DS.getStorageClassSpecLoc(),
8987 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00008988 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00008989 }
Eli Friedman63054b32009-04-19 20:27:55 +00008990
Richard Smithec642442013-04-12 22:46:28 +00008991 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
8992 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
8993 << DeclSpec::getSpecifierName(TSCS);
8994 if (DS.isConstexprSpecified())
8995 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008996 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00008997
Richard Smithec642442013-04-12 22:46:28 +00008998 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00008999
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009000 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009001 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009002
David Blaikie4e4d0842012-03-11 07:00:24 +00009003 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009004 // Check that there are no default arguments inside the type of this
9005 // parameter.
9006 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009007
9008 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9009 if (D.getCXXScopeSpec().isSet()) {
9010 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9011 << D.getCXXScopeSpec().getRange();
9012 D.getCXXScopeSpec().clear();
9013 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009014 }
9015
Sean Hunt7533a5b2010-11-03 01:07:06 +00009016 // Ensure we have a valid name
9017 IdentifierInfo *II = 0;
9018 if (D.hasName()) {
9019 II = D.getIdentifier();
9020 if (!II) {
9021 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9022 << GetNameForDeclarator(D).getName().getAsString();
9023 D.setInvalidType(true);
9024 }
9025 }
9026
Chris Lattnerd84aac12010-02-22 00:40:25 +00009027 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009028 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009029 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9030 ForRedeclaration);
9031 LookupName(R, S);
9032 if (R.isSingleResult()) {
9033 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009034 if (PrevDecl->isTemplateParameter()) {
9035 // Maybe we will complain about the shadowed template parameter.
9036 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9037 // Just pretend that we didn't see the previous declaration.
9038 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009039 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009040 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009041 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009042
Chris Lattnercf79b012009-01-21 02:38:50 +00009043 // Recover by removing the name
9044 II = 0;
9045 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009046 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009047 }
Chris Lattner04421082008-04-08 04:40:51 +00009048 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009049 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009050
John McCall7a9813c2010-01-22 00:28:27 +00009051 // Temporarily put parameter variables in the translation unit, not
9052 // the enclosing context. This prevents them from accidentally
9053 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009054 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009055 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009056 D.getIdentifierLoc(), II,
9057 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009058 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009059
Chris Lattnereaaebc72009-04-25 08:06:05 +00009060 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009061 New->setInvalidDecl();
9062
9063 assert(S->isFunctionPrototypeScope());
9064 assert(S->getFunctionPrototypeDepth() >= 1);
9065 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9066 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009067
Douglas Gregor44b43212008-12-11 16:49:14 +00009068 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009069 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009070 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009071 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009072
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009073 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009074
Douglas Gregore3895852011-09-12 18:37:38 +00009075 if (D.getDeclSpec().isModulePrivateSpecified())
9076 Diag(New->getLocation(), diag::err_module_private_local)
9077 << 1 << New->getDeclName()
9078 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9079 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9080
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009081 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009082 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9083 }
John McCalld226f652010-08-21 09:40:31 +00009084 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009085}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009086
John McCall82dc0092010-06-04 11:21:44 +00009087/// \brief Synthesizes a variable for a parameter arising from a
9088/// typedef.
9089ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9090 SourceLocation Loc,
9091 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009092 /* FIXME: setting StartLoc == Loc.
9093 Would it be worth to modify callers so as to provide proper source
9094 location for the unnamed parameters, embedding the parameter's type? */
9095 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009096 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009097 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009098 Param->setImplicit();
9099 return Param;
9100}
9101
John McCallfbce0e12010-08-24 09:05:15 +00009102void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9103 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009104 // Don't diagnose unused-parameter errors in template instantiations; we
9105 // will already have done so in the template itself.
9106 if (!ActiveTemplateInstantiations.empty())
9107 return;
9108
9109 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009110 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009111 !(*Param)->hasAttr<UnusedAttr>()) {
9112 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9113 << (*Param)->getDeclName();
9114 }
9115 }
9116}
9117
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009118void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9119 ParmVarDecl * const *ParamEnd,
9120 QualType ReturnTy,
9121 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009122 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009123 return;
9124
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009125 // Warn if the return value is pass-by-value and larger than the specified
9126 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009127 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009128 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009129 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009130 Diag(D->getLocation(), diag::warn_return_value_size)
9131 << D->getDeclName() << Size;
9132 }
9133
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009134 // Warn if any parameter is pass-by-value and larger than the specified
9135 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009136 for (; Param != ParamEnd; ++Param) {
9137 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009138 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009139 continue;
9140 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009141 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009142 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9143 << (*Param)->getDeclName() << Size;
9144 }
9145}
9146
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009147ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9148 SourceLocation NameLoc, IdentifierInfo *Name,
9149 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009150 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009151 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009152 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009153 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009154 T->isObjCLifetimeType()) {
9155
9156 Qualifiers::ObjCLifetime lifetime;
9157
9158 // Special cases for arrays:
9159 // - if it's const, use __unsafe_unretained
9160 // - otherwise, it's an error
9161 if (T->isArrayType()) {
9162 if (!T.isConstQualified()) {
9163 DelayedDiagnostics.add(
9164 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009165 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009166 }
9167 lifetime = Qualifiers::OCL_ExplicitNone;
9168 } else {
9169 lifetime = T->getObjCARCImplicitLifetime();
9170 }
9171 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009172 }
9173
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009174 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009175 Context.getAdjustedParameterType(T),
9176 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009177 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009178
9179 // Parameters can not be abstract class types.
9180 // For record types, this is done by the AbstractClassUsageDiagnoser once
9181 // the class has been completely parsed.
9182 if (!CurContext->isRecord() &&
9183 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9184 AbstractParamType))
9185 New->setInvalidDecl();
9186
9187 // Parameter declarators cannot be interface types. All ObjC objects are
9188 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009189 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009190 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009191 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009192 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009193 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009194 T = Context.getObjCObjectPointerType(T);
9195 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009196 }
9197
9198 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9199 // duration shall not be qualified by an address-space qualifier."
9200 // Since all parameters have automatic store duration, they can not have
9201 // an address space.
9202 if (T.getAddressSpace() != 0) {
9203 Diag(NameLoc, diag::err_arg_with_address_space);
9204 New->setInvalidDecl();
9205 }
9206
9207 return New;
9208}
9209
Douglas Gregora3a83512009-04-01 23:51:29 +00009210void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9211 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009212 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009213
Reid Spencer5f016e22007-07-11 17:01:13 +00009214 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9215 // for a K&R function.
9216 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009217 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9218 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009219 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009220 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009221 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009222 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009223 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009224 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009225 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009226 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009227
Reid Spencer5f016e22007-07-11 17:01:13 +00009228 // Implicitly declare the argument as type 'int' for lack of a better
9229 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009230 AttributeFactory attrs;
9231 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009232 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009233 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009234 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009235 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009236 // Use the identifier location for the type source range.
9237 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9238 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009239 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9240 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009241 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009242 }
9243 }
Mike Stump1eb44332009-09-09 15:08:12 +00009244 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009245}
9246
Richard Smith87162c22012-04-17 22:30:01 +00009247Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009248 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009249 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009250 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009251
Douglas Gregor45fa5602011-11-07 20:56:01 +00009252 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009253 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009254 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009255}
9256
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009257static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9258 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009259 // Don't warn about invalid declarations.
9260 if (FD->isInvalidDecl())
9261 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009262
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009263 // Or declarations that aren't global.
9264 if (!FD->isGlobal())
9265 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009266
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009267 // Don't warn about C++ member functions.
9268 if (isa<CXXMethodDecl>(FD))
9269 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009270
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009271 // Don't warn about 'main'.
9272 if (FD->isMain())
9273 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009274
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009275 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009276 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009277 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009278
9279 // Don't warn about function templates.
9280 if (FD->getDescribedFunctionTemplate())
9281 return false;
9282
9283 // Don't warn about function template specializations.
9284 if (FD->isFunctionTemplateSpecialization())
9285 return false;
9286
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009287 // Don't warn for OpenCL kernels.
9288 if (FD->hasAttr<OpenCLKernelAttr>())
9289 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009290
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009291 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009292 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9293 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009294 // Ignore any declarations that occur in function or method
9295 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009296 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009297 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009298
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009299 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009300 if (FD->getNumParams() == 0)
9301 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009302 break;
9303 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009304
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009305 return MissingPrototype;
9306}
9307
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009308void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
9309 // Don't complain if we're in GNU89 mode and the previous definition
9310 // was an extern inline function.
9311 const FunctionDecl *Definition;
Sean Hunt10620eb2011-05-06 20:44:56 +00009312 if (FD->isDefined(Definition) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009313 !canRedefineFunction(Definition, getLangOpts())) {
9314 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009315 Definition->getStorageClass() == SC_Extern)
9316 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009317 << FD->getDeclName() << getLangOpts().CPlusPlus;
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009318 else
9319 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9320 Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smitheef00292012-08-06 02:25:10 +00009321 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009322 }
9323}
9324
John McCalld226f652010-08-21 09:40:31 +00009325Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009326 // Clear the last template instantiation error context.
9327 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9328
Douglas Gregor52591bf2009-06-24 00:54:41 +00009329 if (!D)
9330 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009331 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009332
John McCalld226f652010-08-21 09:40:31 +00009333 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009334 FD = FunTmpl->getTemplatedDecl();
9335 else
John McCalld226f652010-08-21 09:40:31 +00009336 FD = cast<FunctionDecl>(D);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009337
Manuel Klimek152b4e42013-08-22 12:12:24 +00009338 // Enter a new function scope
9339 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009340
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009341 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009342 if (!FD->isLateTemplateParsed())
9343 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009344
Douglas Gregorcda9c672009-02-16 17:45:42 +00009345 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009346 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009347 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9348 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009349 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009350 FD->setInvalidDecl();
9351 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009352 }
9353
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009354 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009355 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9356 QualType ResultType = FD->getResultType();
9357 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009358 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009359 RequireCompleteType(FD->getLocation(), ResultType,
9360 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009361 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009362
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009363 // GNU warning -Wmissing-prototypes:
9364 // Warn if a global function is defined without a previous
9365 // prototype declaration. This warning is issued even if the
9366 // definition itself provides a prototype. The aim is to detect
9367 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009368 const FunctionDecl *PossibleZeroParamPrototype = 0;
9369 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009370 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009371
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009372 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009373 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009374 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009375 if (TypeSourceInfo *TI =
9376 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9377 TypeLoc TL = TI->getTypeLoc();
9378 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9379 Diag(PossibleZeroParamPrototype->getLocation(),
9380 diag::note_declaration_not_a_prototype)
9381 << PossibleZeroParamPrototype
9382 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9383 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009384 }
9385 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009386
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009387 if (FnBodyScope)
9388 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009389
Chris Lattner04421082008-04-08 04:40:51 +00009390 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009391 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9392 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009393
9394 // Introduce our parameters into the function scope
9395 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9396 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009397 Param->setOwningFunction(FD);
9398
Chris Lattner04421082008-04-08 04:40:51 +00009399 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009400 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009401 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009402
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009403 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009404 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009405 }
Chris Lattner04421082008-04-08 04:40:51 +00009406
James Molloy16f1f712012-02-29 10:24:19 +00009407 // If we had any tags defined in the function prototype,
9408 // introduce them into the function scope.
9409 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009410 for (ArrayRef<NamedDecl *>::iterator
9411 I = FD->getDeclsInPrototypeScope().begin(),
9412 E = FD->getDeclsInPrototypeScope().end();
9413 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009414 NamedDecl *D = *I;
9415
9416 // Some of these decls (like enums) may have been pinned to the translation unit
9417 // for lack of a real context earlier. If so, remove from the translation unit
9418 // and reattach to the current context.
9419 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9420 // Is the decl actually in the context?
9421 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9422 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9423 if (*DI == D) {
9424 Context.getTranslationUnitDecl()->removeDecl(D);
9425 break;
9426 }
9427 }
9428 // Either way, reassign the lexical decl context to our FunctionDecl.
9429 D->setLexicalDeclContext(CurContext);
9430 }
9431
9432 // If the decl has a non-null name, make accessible in the current scope.
9433 if (!D->getName().empty())
9434 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9435
9436 // Similarly, dive into enums and fish their constants out, making them
9437 // accessible in this scope.
9438 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9439 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9440 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009441 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009442 }
9443 }
9444 }
9445
Richard Smith87162c22012-04-17 22:30:01 +00009446 // Ensure that the function's exception specification is instantiated.
9447 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9448 ResolveExceptionSpec(D->getLocation(), FPT);
9449
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009450 // Checking attributes of current function definition
9451 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009452 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9453 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9454 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009455 // Microsoft accepts dllimport for functions defined within class scope.
9456 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009457 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009458 Diag(FD->getLocation(),
9459 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9460 << "dllimport";
9461 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009462 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009463 }
9464
9465 // Visual C++ appears to not think this is an issue, so only issue
9466 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009467 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009468 // If a symbol previously declared dllimport is later defined, the
9469 // attribute is ignored in subsequent references, and a warning is
9470 // emitted.
9471 Diag(FD->getLocation(),
9472 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009473 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009474 }
9475 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009476 // We want to attach documentation to original Decl (which might be
9477 // a function template).
9478 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009479 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009480}
9481
Douglas Gregor5077c382010-05-15 06:01:05 +00009482/// \brief Given the set of return statements within a function body,
9483/// compute the variables that are subject to the named return value
9484/// optimization.
9485///
9486/// Each of the variables that is subject to the named return value
9487/// optimization will be marked as NRVO variables in the AST, and any
9488/// return statement that has a marked NRVO variable as its NRVO candidate can
9489/// use the named return value optimization.
9490///
9491/// This function applies a very simplistic algorithm for NRVO: if every return
9492/// statement in the function has the same NRVO candidate, that candidate is
9493/// the NRVO variable.
9494///
9495/// FIXME: Employ a smarter algorithm that accounts for multiple return
9496/// statements and the lifetimes of the NRVO candidates. We should be able to
9497/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009498void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009499 ReturnStmt **Returns = Scope->Returns.data();
9500
Douglas Gregor5077c382010-05-15 06:01:05 +00009501 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009502 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009503 if (!Returns[I]->getNRVOCandidate())
9504 return;
9505
9506 if (!NRVOCandidate)
9507 NRVOCandidate = Returns[I]->getNRVOCandidate();
9508 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9509 return;
9510 }
9511
9512 if (NRVOCandidate)
9513 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9514}
9515
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009516bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009517 if (!Consumer.shouldSkipFunctionBody(D))
9518 return false;
9519
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009520 if (isa<ObjCMethodDecl>(D))
9521 return true;
9522
9523 FunctionDecl *FD = 0;
9524 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9525 FD = FTD->getTemplatedDecl();
9526 else
9527 FD = cast<FunctionDecl>(D);
9528
9529 // We cannot skip the body of a function (or function template) which is
9530 // constexpr, since we may need to evaluate its body in order to parse the
9531 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009532 // We cannot skip the body of a function with an undeduced return type,
9533 // because any callers of that function need to know the type.
9534 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009535}
9536
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009537Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009538 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009539 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009540 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009541 MD->setHasSkippedBody();
9542 return ActOnFinishFunctionBody(Decl, 0);
9543}
9544
John McCallf312b1e2010-08-26 23:41:50 +00009545Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009546 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009547}
9548
John McCall9ae2f072010-08-23 23:25:46 +00009549Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9550 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009551 FunctionDecl *FD = 0;
9552 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9553 if (FunTmpl)
9554 FD = FunTmpl->getTemplatedDecl();
9555 else
9556 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9557
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009558 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009559 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009560
Douglas Gregord83d0402009-08-22 00:34:47 +00009561 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009562 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009563
Richard Smith25d8c852013-05-10 04:31:10 +00009564 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9565 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9566 // If the function has a deduced result type but contains no 'return'
9567 // statements, the result type as written must be exactly 'auto', and
9568 // the deduced result type is 'void'.
9569 if (!FD->getResultType()->getAs<AutoType>()) {
9570 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9571 << FD->getResultType();
9572 FD->setInvalidDecl();
9573 } else {
9574 // Substitute 'void' for the 'auto' in the type.
9575 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9576 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9577 Context.adjustDeducedFunctionResultType(
9578 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009579 }
9580 }
9581
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009582 // The only way to be included in UndefinedButUsed is if there is an
9583 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009584 // is the first declaration.
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009585 if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009586 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009587 UndefinedButUsed.erase(FD);
9588 else if (FD->isInlined() &&
9589 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9590 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9591 UndefinedButUsed.erase(FD);
9592 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009593
John McCall75d8ba32012-02-14 19:50:52 +00009594 // If the function implicitly returns zero (like 'main') or is naked,
9595 // don't complain about missing return statements.
9596 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009597 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009598
Francois Pichet6a247472011-05-11 02:14:46 +00009599 // MSVC permits the use of pure specifier (=0) on function definition,
9600 // defined at class scope, warn about this non standard construct.
David Blaikie4e4d0842012-03-11 07:00:24 +00009601 if (getLangOpts().MicrosoftExt && FD->isPure())
Francois Pichet6a247472011-05-11 02:14:46 +00009602 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9603
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009604 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009605 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009606 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9607 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009608
9609 // If this is a constructor, we need a vtable.
9610 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9611 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009612
Jordan Rose7dd900e2012-07-02 21:19:23 +00009613 // Try to apply the named return value optimization. We have to check
9614 // if we can do this here because lambdas keep return statements around
9615 // to deduce an implicit return type.
9616 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9617 !FD->isDependentContext())
9618 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009619 }
9620
Douglas Gregor76e3da52012-02-08 20:17:14 +00009621 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9622 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009623 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009624 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009625 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009626 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009627 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009628 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9629 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009630
9631 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009632 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009633 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009634 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009635 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9636 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009637 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009638 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009639 } else {
John McCalld226f652010-08-21 09:40:31 +00009640 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009641 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009642
Jordan Rose535a5d02012-10-19 16:05:26 +00009643 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009644 "This should only be set for ObjC methods, which should have been "
9645 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009646
Reid Spencer5f016e22007-07-11 17:01:13 +00009647 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009648 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009649 // C++ constructors that have function-try-blocks can't have return
9650 // statements in the handlers of that block. (C++ [except.handle]p14)
9651 // Verify this.
9652 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9653 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9654
Richard Smith37bee672011-08-12 18:44:32 +00009655 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009656 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009657 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009658 !hasAnyUnrecoverableErrorsInThisFunction() &&
9659 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009660 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009661
John McCall15442822010-08-04 01:04:25 +00009662 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9663 if (!Destructor->getParent()->isDependentType())
9664 CheckDestructor(Destructor);
9665
John McCallef027fe2010-03-16 21:39:52 +00009666 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9667 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009668 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009669
9670 // If any errors have occurred, clear out any temporaries that may have
9671 // been leftover. This ensures that these temporaries won't be picked up for
9672 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009673 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009674 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009675 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009676 }
9677 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9678 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009679 // Since the body is valid, issue any analysis-based warnings that are
9680 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009681 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009682 }
9683
Richard Smith86c3ae42012-02-13 03:54:03 +00009684 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9685 (!CheckConstexprFunctionDecl(FD) ||
9686 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009687 FD->setInvalidDecl();
9688
John McCall80ee6e82011-11-10 05:35:25 +00009689 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009690 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009691 assert(MaybeODRUseExprs.empty() &&
9692 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009693 }
9694
John McCall90f97892010-03-25 22:08:03 +00009695 if (!IsInstantiation)
9696 PopDeclContext();
9697
Eli Friedmanec9ea722012-01-05 03:35:19 +00009698 PopFunctionScopeInfo(ActivePolicy, dcl);
Anders Carlssonf8a9a792009-11-13 19:21:49 +00009699
Douglas Gregord5b57282009-11-15 07:07:58 +00009700 // If any errors have occurred, clear out any temporaries that may have
9701 // been leftover. This ensures that these temporaries won't be picked up for
9702 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009703 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009704 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009705 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009706
John McCalld226f652010-08-21 09:40:31 +00009707 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009708}
9709
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009710
9711/// When we finish delayed parsing of an attribute, we must attach it to the
9712/// relevant Decl.
9713void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9714 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009715 // Always attach attributes to the underlying decl.
9716 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9717 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009718 ProcessDeclAttributeList(S, D, Attrs.getList());
9719
9720 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9721 if (Method->isStatic())
9722 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009723}
9724
9725
Reid Spencer5f016e22007-07-11 17:01:13 +00009726/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9727/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009728NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009729 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009730 // Before we produce a declaration for an implicitly defined
9731 // function, see whether there was a locally-scoped declaration of
9732 // this name as a function or variable. If so, use that
9733 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009734 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9735 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9736 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9737 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009738 }
9739
Chris Lattner37d10842008-05-05 21:18:06 +00009740 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009741 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009742 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009743 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009744 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009745 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009746 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009747 diag_id = diag::warn_implicit_function_decl;
9748 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009749
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009750 // Because typo correction is expensive, only do it if the implicit
9751 // function declaration is going to be treated as an error.
9752 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9753 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009754 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009755 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009756 LookupOrdinaryName, S, 0, Validator)))
9757 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9758 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009759 }
9760
Reid Spencer5f016e22007-07-11 17:01:13 +00009761 // Set a Declarator for the implicit definition: int foo();
9762 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009763 AttributeFactory attrFactory;
9764 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009765 unsigned DiagID;
9766 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009767 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009768 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009769 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009770 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009771 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9772 /*IsAmbiguous=*/false,
9773 /*RParenLoc=*/NoLoc,
9774 /*ArgInfo=*/0,
9775 /*NumArgs=*/0,
9776 /*EllipsisLoc=*/NoLoc,
9777 /*RParenLoc=*/NoLoc,
9778 /*TypeQuals=*/0,
9779 /*RefQualifierIsLvalueRef=*/true,
9780 /*RefQualifierLoc=*/NoLoc,
9781 /*ConstQualifierLoc=*/NoLoc,
9782 /*VolatileQualifierLoc=*/NoLoc,
9783 /*MutableLoc=*/NoLoc,
9784 EST_None,
9785 /*ESpecLoc=*/NoLoc,
9786 /*Exceptions=*/0,
9787 /*ExceptionRanges=*/0,
9788 /*NumExceptions=*/0,
9789 /*NoexceptExpr=*/0,
9790 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009791 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009792 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009793 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009794
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009795 // Insert this function into translation-unit scope.
9796
9797 DeclContext *PrevDC = CurContext;
9798 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009799
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009800 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009801 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009802
9803 CurContext = PrevDC;
9804
Douglas Gregor3c385e52009-02-14 18:57:46 +00009805 AddKnownFunctionAttributes(FD);
9806
Steve Naroffe2ef8152008-04-04 14:32:09 +00009807 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009808}
9809
Douglas Gregor3c385e52009-02-14 18:57:46 +00009810/// \brief Adds any function attributes that we know a priori based on
9811/// the declaration of this function.
9812///
9813/// These attributes can apply both to implicitly-declared builtins
9814/// (like __builtin___printf_chk) or to library-declared functions
9815/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009816///
9817/// We need to check for duplicate attributes both here and where user-written
9818/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009819void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9820 if (FD->isInvalidDecl())
9821 return;
9822
9823 // If this is a built-in function, map its builtin attributes to
9824 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009825 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00009826 // Handle printf-formatting attributes.
9827 unsigned FormatIdx;
9828 bool HasVAListArg;
9829 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009830 if (!FD->getAttr<FormatAttr>()) {
9831 const char *fmt = "printf";
9832 unsigned int NumParams = FD->getNumParams();
9833 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9834 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9835 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +00009836 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009837 &Context.Idents.get(fmt),
9838 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00009839 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009840 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00009841 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00009842 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9843 HasVAListArg)) {
9844 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009845 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009846 &Context.Idents.get("scanf"),
9847 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00009848 HasVAListArg ? 0 : FormatIdx+2));
9849 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009850
9851 // Mark const if we don't care about errno and that is the only
9852 // thing preventing the function from being const. This allows
9853 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +00009854 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009855 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009856 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009857 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009858 }
Mike Stump0feecbb2009-07-27 19:14:18 +00009859
Rafael Espindola67004152011-10-12 19:51:18 +00009860 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
9861 !FD->getAttr<ReturnsTwiceAttr>())
9862 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009863 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009864 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009865 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009866 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +00009867 }
9868
9869 IdentifierInfo *Name = FD->getIdentifier();
9870 if (!Name)
9871 return;
David Blaikie4e4d0842012-03-11 07:00:24 +00009872 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00009873 FD->getDeclContext()->isTranslationUnit()) ||
9874 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00009875 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +00009876 LinkageSpecDecl::lang_c)) {
9877 // Okay: this could be a libc/libm/Objective-C function we know
9878 // about.
9879 } else
9880 return;
9881
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009882 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00009883 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +00009884 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009885 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009886 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009887 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +00009888 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +00009889 }
Jordan Rose8a64f882012-08-08 21:17:31 +00009890
9891 if (Name->isStr("__CFStringMakeConstantString")) {
9892 // We already have a __builtin___CFStringMakeConstantString,
9893 // but builds that use -fno-constant-cfstrings don't go through that.
9894 if (!FD->getAttr<FormatArgAttr>())
9895 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
9896 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00009897}
Reid Spencer5f016e22007-07-11 17:01:13 +00009898
John McCallba6a9bd2009-10-24 08:00:42 +00009899TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00009900 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00009901 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00009902 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +00009903
John McCalla93c9342009-12-07 02:54:59 +00009904 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +00009905 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +00009906 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +00009907 }
9908
Reid Spencer5f016e22007-07-11 17:01:13 +00009909 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00009910 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009911 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +00009912 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00009913 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +00009914 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00009915
John McCallcde5a402011-02-01 08:20:08 +00009916 // Bail out immediately if we have an invalid declaration.
9917 if (D.isInvalidType()) {
9918 NewTD->setInvalidDecl();
9919 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +00009920 }
9921
Douglas Gregore3895852011-09-12 18:37:38 +00009922 if (D.getDeclSpec().isModulePrivateSpecified()) {
9923 if (CurContext->isFunctionOrMethod())
9924 Diag(NewTD->getLocation(), diag::err_module_private_local)
9925 << 2 << NewTD->getDeclName()
9926 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9927 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9928 else
9929 NewTD->setModulePrivate();
9930 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00009931
John McCallcde5a402011-02-01 08:20:08 +00009932 // C++ [dcl.typedef]p8:
9933 // If the typedef declaration defines an unnamed class (or
9934 // enum), the first typedef-name declared by the declaration
9935 // to be that class type (or enum type) is used to denote the
9936 // class type (or enum type) for linkage purposes only.
9937 // We need to check whether the type was declared in the declaration.
9938 switch (D.getDeclSpec().getTypeSpecType()) {
9939 case TST_enum:
9940 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +00009941 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +00009942 case TST_union:
9943 case TST_class: {
9944 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
9945
9946 // Do nothing if the tag is not anonymous or already has an
9947 // associated typedef (from an earlier typedef in this decl group).
9948 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +00009949 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +00009950
9951 // A well-formed anonymous tag must always be a TUK_Definition.
9952 assert(tagFromDeclSpec->isThisDeclarationADefinition());
9953
9954 // The type must match the tag exactly; no qualifiers allowed.
9955 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
9956 break;
9957
9958 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +00009959 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +00009960 break;
9961 }
9962
9963 default:
9964 break;
9965 }
9966
Steve Naroff5912a352007-08-28 20:14:24 +00009967 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009968}
9969
Douglas Gregor501c5ce2009-05-14 16:41:31 +00009970
Richard Smithf1c66b42012-03-14 23:13:10 +00009971/// \brief Check that this is a valid underlying type for an enum declaration.
9972bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
9973 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
9974 QualType T = TI->getType();
9975
Eli Friedman2fcff832012-12-18 02:37:32 +00009976 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +00009977 return false;
9978
Eli Friedman2fcff832012-12-18 02:37:32 +00009979 if (const BuiltinType *BT = T->getAs<BuiltinType>())
9980 if (BT->isInteger())
9981 return false;
9982
Richard Smithf1c66b42012-03-14 23:13:10 +00009983 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
9984 return true;
9985}
9986
9987/// Check whether this is a valid redeclaration of a previous enumeration.
9988/// \return true if the redeclaration was invalid.
9989bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
9990 QualType EnumUnderlyingTy,
9991 const EnumDecl *Prev) {
9992 bool IsFixed = !EnumUnderlyingTy.isNull();
9993
9994 if (IsScoped != Prev->isScoped()) {
9995 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
9996 << Prev->isScoped();
9997 Diag(Prev->getLocation(), diag::note_previous_use);
9998 return true;
9999 }
10000
10001 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010002 if (!EnumUnderlyingTy->isDependentType() &&
10003 !Prev->getIntegerType()->isDependentType() &&
10004 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010005 Prev->getIntegerType())) {
10006 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10007 << EnumUnderlyingTy << Prev->getIntegerType();
10008 Diag(Prev->getLocation(), diag::note_previous_use);
10009 return true;
10010 }
10011 } else if (IsFixed != Prev->isFixed()) {
10012 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10013 << Prev->isFixed();
10014 Diag(Prev->getLocation(), diag::note_previous_use);
10015 return true;
10016 }
10017
10018 return false;
10019}
10020
Joao Matos6666ed42012-08-31 18:45:21 +000010021/// \brief Get diagnostic %select index for tag kind for
10022/// redeclaration diagnostic message.
10023/// WARNING: Indexes apply to particular diagnostics only!
10024///
10025/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010026static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010027 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010028 case TTK_Struct: return 0;
10029 case TTK_Interface: return 1;
10030 case TTK_Class: return 2;
10031 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010032 }
Joao Matos6666ed42012-08-31 18:45:21 +000010033}
10034
10035/// \brief Determine if tag kind is a class-key compatible with
10036/// class for redeclaration (class, struct, or __interface).
10037///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010038/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010039static bool isClassCompatTagKind(TagTypeKind Tag)
10040{
10041 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10042}
10043
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010044/// \brief Determine whether a tag with a given kind is acceptable
10045/// as a redeclaration of the given tag declaration.
10046///
10047/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010048bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010049 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010050 SourceLocation NewTagLoc,
10051 const IdentifierInfo &Name) {
10052 // C++ [dcl.type.elab]p3:
10053 // The class-key or enum keyword present in the
10054 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010055 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010056 // refers. This rule also applies to the form of
10057 // elaborated-type-specifier that declares a class-name or
10058 // friend class since it can be construed as referring to the
10059 // definition of the class. Thus, in any
10060 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010061 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010062 // used to refer to a union (clause 9), and either the class or
10063 // struct class-key shall be used to refer to a class (clause 9)
10064 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010065 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010066 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010067 if (OldTag == NewTag)
10068 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010069
Joao Matos6666ed42012-08-31 18:45:21 +000010070 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010071 // Warn about the struct/class tag mismatch.
10072 bool isTemplate = false;
10073 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10074 isTemplate = Record->getDescribedClassTemplate();
10075
Richard Trieubbf34c02011-06-10 03:11:26 +000010076 if (!ActiveTemplateInstantiations.empty()) {
10077 // In a template instantiation, do not offer fix-its for tag mismatches
10078 // since they usually mess up the template instead of fixing the problem.
10079 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010080 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10081 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010082 return true;
10083 }
10084
10085 if (isDefinition) {
10086 // On definitions, check previous tags and issue a fix-it for each
10087 // one that doesn't match the current tag.
10088 if (Previous->getDefinition()) {
10089 // Don't suggest fix-its for redefinitions.
10090 return true;
10091 }
10092
10093 bool previousMismatch = false;
10094 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10095 E(Previous->redecls_end()); I != E; ++I) {
10096 if (I->getTagKind() != NewTag) {
10097 if (!previousMismatch) {
10098 previousMismatch = true;
10099 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010100 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10101 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010102 }
10103 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010104 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010105 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010106 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010107 }
10108 }
10109 return true;
10110 }
10111
10112 // Check for a previous definition. If current tag and definition
10113 // are same type, do nothing. If no definition, but disagree with
10114 // with previous tag type, give a warning, but no fix-it.
10115 const TagDecl *Redecl = Previous->getDefinition() ?
10116 Previous->getDefinition() : Previous;
10117 if (Redecl->getTagKind() == NewTag) {
10118 return true;
10119 }
10120
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010121 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010122 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10123 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010124 Diag(Redecl->getLocation(), diag::note_previous_use);
10125
10126 // If there is a previous defintion, suggest a fix-it.
10127 if (Previous->getDefinition()) {
10128 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010129 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010130 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010131 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010132 }
10133
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010134 return true;
10135 }
10136 return false;
10137}
10138
Steve Naroff08d92e42007-09-15 18:49:24 +000010139/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010140/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010141/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010142/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010143Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010144 SourceLocation KWLoc, CXXScopeSpec &SS,
10145 IdentifierInfo *Name, SourceLocation NameLoc,
10146 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010147 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010148 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010149 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010150 SourceLocation ScopedEnumKWLoc,
10151 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010152 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010153 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010154 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010155 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010156 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010157 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010158
Douglas Gregor402abb52009-05-28 23:31:59 +000010159 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010160 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010161 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010162
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010163 // FIXME: Check explicit specializations more carefully.
10164 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010165 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010166
10167 // We only need to do this matching if we have template parameters
10168 // or a scope specifier, which also conveniently avoids this work
10169 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010170 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010171 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010172 if (TemplateParameterList *TemplateParams =
10173 MatchTemplateParametersToScopeSpecifier(
10174 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10175 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010176 if (Kind == TTK_Enum) {
10177 Diag(KWLoc, diag::err_enum_template);
10178 return 0;
10179 }
10180
Douglas Gregord85bea22009-09-26 06:47:28 +000010181 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010182 // This is a declaration or definition of a class template (which may
10183 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010184
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010185 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010186 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010187
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010188 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010189 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010190 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010191 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010192 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010193 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010194 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010195 return Result.get();
10196 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010197 // The "template<>" header is extraneous.
10198 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010199 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010200 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010201 }
Mike Stump1eb44332009-09-09 15:08:12 +000010202 }
10203 }
10204
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010205 // Figure out the underlying type if this a enum declaration. We need to do
10206 // this early, because it's needed to detect if this is an incompatible
10207 // redeclaration.
10208 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10209
10210 if (Kind == TTK_Enum) {
10211 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10212 // No underlying type explicitly specified, or we failed to parse the
10213 // type, default to int.
10214 EnumUnderlying = Context.IntTy.getTypePtr();
10215 else if (UnderlyingType.get()) {
10216 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10217 // integral type; any cv-qualification is ignored.
10218 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010219 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010220 EnumUnderlying = TI;
10221
Richard Smithf1c66b42012-03-14 23:13:10 +000010222 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010223 // Recover by falling back to int.
10224 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010225
Richard Smithf1c66b42012-03-14 23:13:10 +000010226 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010227 UPPC_FixedUnderlyingType))
10228 EnumUnderlying = Context.IntTy.getTypePtr();
10229
David Blaikie4e4d0842012-03-11 07:00:24 +000010230 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010231 // Microsoft enums are always of int type.
10232 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010233 }
10234
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010235 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010236 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010237 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010238
Chandler Carruth7bf36002010-03-01 21:17:36 +000010239 RedeclarationKind Redecl = ForRedeclaration;
10240 if (TUK == TUK_Friend || TUK == TUK_Reference)
10241 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010242
10243 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010244 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010245 if (Name && SS.isNotEmpty()) {
10246 // We have a nested-name tag ('struct foo::bar').
10247
10248 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010249 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010250 Name = 0;
10251 goto CreateNewDecl;
10252 }
10253
John McCallc4e70192009-09-11 04:59:25 +000010254 // If this is a friend or a reference to a class in a dependent
10255 // context, don't try to make a decl for it.
10256 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10257 DC = computeDeclContext(SS, false);
10258 if (!DC) {
10259 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010260 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010261 }
John McCall77bb1aa2010-05-01 00:40:08 +000010262 } else {
10263 DC = computeDeclContext(SS, true);
10264 if (!DC) {
10265 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10266 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010267 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010268 }
John McCallc4e70192009-09-11 04:59:25 +000010269 }
10270
John McCall77bb1aa2010-05-01 00:40:08 +000010271 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010272 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010273
Douglas Gregor1931b442009-02-03 00:34:39 +000010274 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010275 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010276 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010277
John McCall68263142009-11-18 22:49:29 +000010278 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010279 return 0;
John McCall6e247262009-10-10 05:48:19 +000010280
John McCall68263142009-11-18 22:49:29 +000010281 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010282 // Name lookup did not find anything. However, if the
10283 // nested-name-specifier refers to the current instantiation,
10284 // and that current instantiation has any dependent base
10285 // classes, we might find something at instantiation time: treat
10286 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010287 // But this only makes any sense for reference-like lookups.
10288 if (Previous.wasNotFoundInCurrentInstantiation() &&
10289 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010290 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010291 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010292 }
10293
10294 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010295 Diag(NameLoc, diag::err_not_tag_in_scope)
10296 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010297 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010298 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010299 goto CreateNewDecl;
10300 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010301 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010302 // If this is a named struct, check to see if there was a previous forward
10303 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010304 // FIXME: We're looking into outer scopes here, even when we
10305 // shouldn't be. Doing so can result in ambiguities that we
10306 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010307 LookupName(Previous, S);
10308
John McCallc96cd7a2013-03-20 01:53:00 +000010309 // When declaring or defining a tag, ignore ambiguities introduced
10310 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010311 if (Previous.isAmbiguous() &&
10312 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010313 LookupResult::Filter F = Previous.makeFilter();
10314 while (F.hasNext()) {
10315 NamedDecl *ND = F.next();
10316 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10317 F.erase();
10318 }
10319 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010320 }
John McCallc96cd7a2013-03-20 01:53:00 +000010321
10322 // C++11 [namespace.memdef]p3:
10323 // If the name in a friend declaration is neither qualified nor
10324 // a template-id and the declaration is a function or an
10325 // elaborated-type-specifier, the lookup to determine whether
10326 // the entity has been previously declared shall not consider
10327 // any scopes outside the innermost enclosing namespace.
10328 //
10329 // Does it matter that this should be by scope instead of by
10330 // semantic context?
10331 if (!Previous.empty() && TUK == TUK_Friend) {
10332 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10333 LookupResult::Filter F = Previous.makeFilter();
10334 while (F.hasNext()) {
10335 NamedDecl *ND = F.next();
10336 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010337 if (DC->isFileContext() &&
10338 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010339 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010340 FriendSawTagOutsideEnclosingNamespace = true;
10341 }
John McCallc96cd7a2013-03-20 01:53:00 +000010342 }
10343 F.done();
10344 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010345
John McCall68263142009-11-18 22:49:29 +000010346 // Note: there used to be some attempt at recovery here.
10347 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010348 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010349
David Blaikie4e4d0842012-03-11 07:00:24 +000010350 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010351 // FIXME: This makes sure that we ignore the contexts associated
10352 // with C structs, unions, and enums when looking for a matching
10353 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010354 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010355 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10356 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010357 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010358 } else if (S->isFunctionPrototypeScope()) {
10359 // If this is an enum declaration in function prototype scope, set its
10360 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010361 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010362 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010363 }
10364
John McCall68263142009-11-18 22:49:29 +000010365 if (Previous.isSingleResult() &&
10366 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010367 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010368 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010369 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010370 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010371 }
10372
David Blaikie4e4d0842012-03-11 07:00:24 +000010373 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010374 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010375 // This is a declaration of or a reference to "std::bad_alloc".
10376 isStdBadAlloc = true;
10377
John McCall68263142009-11-18 22:49:29 +000010378 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010379 // std::bad_alloc has been implicitly declared (but made invisible to
10380 // name lookup). Fill in this implicit declaration as the previous
10381 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010382 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010383 }
10384 }
John McCall68263142009-11-18 22:49:29 +000010385
John McCall9c86b512010-03-25 21:28:06 +000010386 // If we didn't find a previous declaration, and this is a reference
10387 // (or friend reference), move to the correct scope. In C++, we
10388 // also need to do a redeclaration lookup there, just in case
10389 // there's a shadow friend decl.
10390 if (Name && Previous.empty() &&
10391 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10392 if (Invalid) goto CreateNewDecl;
10393 assert(SS.isEmpty());
10394
10395 if (TUK == TUK_Reference) {
10396 // C++ [basic.scope.pdecl]p5:
10397 // -- for an elaborated-type-specifier of the form
10398 //
10399 // class-key identifier
10400 //
10401 // if the elaborated-type-specifier is used in the
10402 // decl-specifier-seq or parameter-declaration-clause of a
10403 // function defined in namespace scope, the identifier is
10404 // declared as a class-name in the namespace that contains
10405 // the declaration; otherwise, except as a friend
10406 // declaration, the identifier is declared in the smallest
10407 // non-class, non-function-prototype scope that contains the
10408 // declaration.
10409 //
10410 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10411 // C structs and unions.
10412 //
10413 // It is an error in C++ to declare (rather than define) an enum
10414 // type, including via an elaborated type specifier. We'll
10415 // diagnose that later; for now, declare the enum in the same
10416 // scope as we would have picked for any other tag type.
10417 //
10418 // GNU C also supports this behavior as part of its incomplete
10419 // enum types extension, while GNU C++ does not.
10420 //
10421 // Find the context where we'll be declaring the tag.
10422 // FIXME: We would like to maintain the current DeclContext as the
10423 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010424 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010425 SearchDC = SearchDC->getParent();
10426
10427 // Find the scope where we'll be declaring the tag.
10428 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010429 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010430 S->isFunctionPrototypeScope()) ||
10431 ((S->getFlags() & Scope::DeclScope) == 0) ||
10432 (S->getEntity() &&
10433 ((DeclContext *)S->getEntity())->isTransparentContext()))
10434 S = S->getParent();
10435 } else {
10436 assert(TUK == TUK_Friend);
10437 // C++ [namespace.memdef]p3:
10438 // If a friend declaration in a non-local class first declares a
10439 // class or function, the friend class or function is a member of
10440 // the innermost enclosing namespace.
10441 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010442 }
10443
John McCall0d6b1642010-04-23 18:46:30 +000010444 // In C++, we need to do a redeclaration lookup to properly
10445 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010446 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010447 Previous.setRedeclarationKind(ForRedeclaration);
10448 LookupQualifiedName(Previous, SearchDC);
10449 }
10450 }
10451
John McCall68263142009-11-18 22:49:29 +000010452 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010453 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010454
10455 // It's okay to have a tag decl in the same scope as a typedef
10456 // which hides a tag decl in the same scope. Finding this
10457 // insanity with a redeclaration lookup can only actually happen
10458 // in C++.
10459 //
10460 // This is also okay for elaborated-type-specifiers, which is
10461 // technically forbidden by the current standard but which is
10462 // okay according to the likely resolution of an open issue;
10463 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010464 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010465 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010466 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10467 TagDecl *Tag = TT->getDecl();
10468 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010469 Tag->getDeclContext()->getRedeclContext()
10470 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010471 PrevDecl = Tag;
10472 Previous.clear();
10473 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010474 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010475 }
10476 }
10477 }
10478 }
10479
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010480 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010481 // If this is a use of a previous tag, or if the tag is already declared
10482 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010483 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010484 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010485 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010486 // Make sure that this wasn't declared as an enum and now used as a
10487 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010488 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10489 TUK == TUK_Definition, KWLoc,
10490 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010491 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010492 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10493 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010494 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010495 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010496 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010497 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10498 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010499 else
10500 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010501 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010502
Mike Stump1eb44332009-09-09 15:08:12 +000010503 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010504 Kind = PrevTagDecl->getTagKind();
10505 else {
10506 // Recover by making this an anonymous redefinition.
10507 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010508 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010509 Invalid = true;
10510 }
10511 }
10512
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010513 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10514 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10515
Richard Smithbdad7a22012-01-10 01:33:14 +000010516 // If this is an elaborated-type-specifier for a scoped enumeration,
10517 // the 'class' keyword is not necessary and not permitted.
10518 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10519 if (ScopedEnum)
10520 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10521 << PrevEnum->isScoped()
10522 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10523 return PrevTagDecl;
10524 }
10525
Richard Smithf1c66b42012-03-14 23:13:10 +000010526 QualType EnumUnderlyingTy;
10527 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10528 EnumUnderlyingTy = TI->getType();
10529 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10530 EnumUnderlyingTy = QualType(T, 0);
10531
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010532 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010533 // returning the previous declaration, unless this is a definition,
10534 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010535 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10536 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010537 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010538 }
10539
David Majnemer2ec2b842013-06-11 03:51:23 +000010540 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010541 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010542 // except that a nested class or member class template can be declared
10543 // and then later defined.
10544 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10545 S->isDeclScope(PrevDecl)) {
10546 Diag(NameLoc, diag::ext_member_redeclared);
10547 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10548 }
10549
Douglas Gregora3a83512009-04-01 23:51:29 +000010550 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010551 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010552
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010553 // FIXME: In the future, return a variant or some other clue
10554 // for the consumer of this Decl to know it doesn't own it.
10555 // For our current ASTs this shouldn't be a problem, but will
10556 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010557 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010558 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010559 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010560
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010561 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010562 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010563 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010564 // If we're defining a specialization and the previous definition
10565 // is from an implicit instantiation, don't emit an error
10566 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010567 bool IsExplicitSpecializationAfterInstantiation = false;
10568 if (isExplicitSpecialization) {
10569 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10570 IsExplicitSpecializationAfterInstantiation =
10571 RD->getTemplateSpecializationKind() !=
10572 TSK_ExplicitSpecialization;
10573 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10574 IsExplicitSpecializationAfterInstantiation =
10575 ED->getTemplateSpecializationKind() !=
10576 TSK_ExplicitSpecialization;
10577 }
10578
10579 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010580 // A redeclaration in function prototype scope in C isn't
10581 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010582 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010583 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10584 else
10585 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010586 Diag(Def->getLocation(), diag::note_previous_definition);
10587 // If this is a redefinition, recover by making this
10588 // struct be anonymous, which will make any later
10589 // references get the previous definition.
10590 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010591 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010592 Invalid = true;
10593 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010594 } else {
10595 // If the type is currently being defined, complain
10596 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010597 const TagType *Tag
10598 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010599 if (Tag->isBeingDefined()) {
10600 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010601 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010602 diag::note_previous_definition);
10603 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010604 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010605 Invalid = true;
10606 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010607 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010608
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010609 // Okay, this is definition of a previously declared or referenced
10610 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010611 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010612 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010613 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010614 // have a definition. Just create a new decl.
10615
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010616 } else {
10617 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010618 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010619 // new decl/type. We set PrevDecl to NULL so that the entities
10620 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010621 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010622 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010623 // If we get here, we're going to create a new Decl. If PrevDecl
10624 // is non-NULL, it's a definition of the tag declared by
10625 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010626
10627
10628 // Otherwise, PrevDecl is not a tag, but was found with tag
10629 // lookup. This is only actually possible in C++, where a few
10630 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010631 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010632 // Use a better diagnostic if an elaborated-type-specifier
10633 // found the wrong kind of type on the first
10634 // (non-redeclaration) lookup.
10635 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10636 !Previous.isForRedeclaration()) {
10637 unsigned Kind = 0;
10638 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010639 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10640 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010641 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10642 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10643 Invalid = true;
10644
10645 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010646 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10647 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010648 // do nothing
10649
10650 // Diagnose implicit declarations introduced by elaborated types.
10651 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10652 unsigned Kind = 0;
10653 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010654 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10655 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010656 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10657 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10658 Invalid = true;
10659
10660 // Otherwise it's a declaration. Call out a particularly common
10661 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010662 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10663 unsigned Kind = 0;
10664 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010665 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010666 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010667 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10668 Invalid = true;
10669
10670 // Otherwise, diagnose.
10671 } else {
10672 // The tag name clashes with something else in the target scope,
10673 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010674 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010675 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010676 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010677 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010678 }
John McCall0d6b1642010-04-23 18:46:30 +000010679
10680 // The existing declaration isn't relevant to us; we're in a
10681 // new scope, so clear out the previous declaration.
10682 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010683 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010684 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010685
Chris Lattnercc98eac2008-12-17 07:13:27 +000010686CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010687
John McCall68263142009-11-18 22:49:29 +000010688 TagDecl *PrevDecl = 0;
10689 if (Previous.isSingleResult())
10690 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10691
Reid Spencer5f016e22007-07-11 17:01:13 +000010692 // If there is an identifier, use the location of the identifier as the
10693 // location of the decl, otherwise use the location of the struct/union
10694 // keyword.
10695 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010696
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010697 // Otherwise, create a new declaration. If there is a previous
10698 // declaration of the same entity, the two will be linked via
10699 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010700 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010701
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010702 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010703 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010704 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10705 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010706 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010707 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010708 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010709 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010710 if (TUK != TUK_Definition && !Invalid) {
10711 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010712 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10713 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010714 // C++0x: 7.2p2: opaque-enum-declaration.
10715 // Conflicts are diagnosed above. Do nothing.
10716 }
10717 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010718 Diag(Loc, diag::ext_forward_ref_enum_def)
10719 << New;
10720 Diag(Def->getLocation(), diag::note_previous_definition);
10721 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010722 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010723 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010724 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010725 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010726 DiagID = diag::err_forward_ref_enum;
10727 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010728
10729 // If this is a forward-declared reference to an enumeration, make a
10730 // note of it; we won't actually be introducing the declaration into
10731 // the declaration context.
10732 if (TUK == TUK_Reference)
10733 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010734 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010735 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010736
10737 if (EnumUnderlying) {
10738 EnumDecl *ED = cast<EnumDecl>(New);
10739 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10740 ED->setIntegerTypeSourceInfo(TI);
10741 else
10742 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10743 ED->setPromotionType(ED->getIntegerType());
10744 }
10745
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010746 } else {
10747 // struct/union/class
10748
Reid Spencer5f016e22007-07-11 17:01:13 +000010749 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10750 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010751 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010752 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010753 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010754 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010755
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010756 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010757 StdBadAlloc = cast<CXXRecordDecl>(New);
10758 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010759 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010760 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010761 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010762
John McCallb6217662010-03-15 10:12:16 +000010763 // Maybe add qualifier info.
10764 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010765 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010766 // If this is either a declaration or a definition, check the
10767 // nested-name-specifier against the current context. We don't do this
10768 // for explicit specializations, because they have similar checking
10769 // (with more specific diagnostics) in the call to
10770 // CheckMemberSpecialization, below.
10771 if (!isExplicitSpecialization &&
10772 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10773 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10774 Invalid = true;
10775
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010776 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010777 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010778 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010779 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010780 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010781 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010782 }
10783 else
10784 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010785 }
10786
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010787 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10788 // Add alignment attributes if necessary; these attributes are checked when
10789 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010790 //
10791 // It is important for implementing the correct semantics that this
10792 // happen here (in act on tag decl). The #pragma pack stack is
10793 // maintained as a result of parser callbacks which can occur at
10794 // many points during the parsing of a struct declaration (because
10795 // the #pragma tokens are effectively skipped over during the
10796 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010797 if (TUK == TUK_Definition) {
10798 AddAlignmentAttributesForRecord(RD);
10799 AddMsStructLayoutForRecord(RD);
10800 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010801 }
10802
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010803 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010804 if (isExplicitSpecialization)
10805 Diag(New->getLocation(), diag::err_module_private_specialization)
10806 << 2
10807 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010808 // __module_private__ does not apply to local classes. However, we only
10809 // diagnose this as an error when the declaration specifiers are
10810 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010811 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010812 New->setModulePrivate();
10813 }
10814
Douglas Gregorf6b11852009-10-08 15:14:33 +000010815 // If this is a specialization of a member class (of a class template),
10816 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000010817 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000010818 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000010819
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010820 if (Invalid)
10821 New->setInvalidDecl();
10822
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010823 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010824 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010825
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010826 // If we're declaring or defining a tag in function prototype scope
10827 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000010828 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000010829 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10830
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010831 // Set the lexical context. If the tag has a C++ scope specifier, the
10832 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000010833 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010834
John McCall02cace72009-08-28 07:59:38 +000010835 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000010836 // In Microsoft mode, a friend declaration also acts as a forward
10837 // declaration so we always pass true to setObjectOfFriendDecl to make
10838 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000010839 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000010840 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10841 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000010842
Anders Carlsson0cf88302009-03-26 01:19:02 +000010843 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000010844 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000010845 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000010846
John McCall0f434ec2009-07-31 02:45:11 +000010847 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010848 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000010849
Reid Spencer5f016e22007-07-11 17:01:13 +000010850 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000010851 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000010852 // We might be replacing an existing declaration in the lookup tables;
10853 // if so, borrow its access specifier.
10854 if (PrevDecl)
10855 New->setAccess(PrevDecl->getAccess());
10856
Sebastian Redl7a126a42010-08-31 00:36:30 +000010857 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010858 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000010859 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000010860 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10861 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000010862 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000010863 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010864 PushOnScopeChains(New, S, !IsForwardReference);
10865 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010866 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010867
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010868 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010869 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000010870 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000010871
Douglas Gregorc29f77b2009-07-07 16:35:42 +000010872 // If this is the C FILE type, notify the AST context.
10873 if (IdentifierInfo *II = New->getIdentifier())
10874 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010875 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000010876 II->isStr("FILE"))
10877 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000010878
James Molloy16f1f712012-02-29 10:24:19 +000010879 // If we were in function prototype scope (and not in C++ mode), add this
10880 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000010881 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000010882 InFunctionDeclarator && Name)
10883 DeclsInPrototypeScope.push_back(New);
10884
Rafael Espindola98ae8342012-05-10 02:50:16 +000010885 if (PrevDecl)
10886 mergeDeclAttributes(New, PrevDecl);
10887
Rafael Espindola71adc5b2012-07-17 15:14:47 +000010888 // If there's a #pragma GCC visibility in scope, set the visibility of this
10889 // record.
10890 AddPushedVisibilityAttribute(New);
10891
Douglas Gregor402abb52009-05-28 23:31:59 +000010892 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000010893 // In C++, don't return an invalid declaration. We can't recover well from
10894 // the cases where we make the type anonymous.
10895 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000010896}
10897
John McCalld226f652010-08-21 09:40:31 +000010898void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010899 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000010900 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000010901
Douglas Gregor72de6672009-01-08 20:45:30 +000010902 // Enter the tag context.
10903 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000010904
10905 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000010906
10907 // If there's a #pragma GCC visibility in scope, set the visibility of this
10908 // record.
10909 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000010910}
Douglas Gregor72de6672009-01-08 20:45:30 +000010911
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000010912Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000010913 assert(isa<ObjCContainerDecl>(IDecl) &&
10914 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
10915 DeclContext *OCD = cast<DeclContext>(IDecl);
10916 assert(getContainingDC(OCD) == CurContext &&
10917 "The next DeclContext should be lexically contained in the current one.");
10918 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000010919 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000010920}
10921
John McCalld226f652010-08-21 09:40:31 +000010922void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000010923 SourceLocation FinalLoc,
John McCallf9368152009-12-20 07:58:13 +000010924 SourceLocation LBraceLoc) {
10925 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000010926 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000010927
John McCallf9368152009-12-20 07:58:13 +000010928 FieldCollector->StartClass();
10929
10930 if (!Record->getIdentifier())
10931 return;
10932
Anders Carlsson2c3ee542011-03-25 14:31:08 +000010933 if (FinalLoc.isValid())
10934 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssondfc2f102011-01-22 17:51:53 +000010935
John McCallf9368152009-12-20 07:58:13 +000010936 // C++ [class]p2:
10937 // [...] The class-name is also inserted into the scope of the
10938 // class itself; this is known as the injected-class-name. For
10939 // purposes of access checking, the injected-class-name is treated
10940 // as if it were a public member name.
10941 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010942 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
10943 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000010944 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000010945 /*PrevDecl=*/0,
10946 /*DelayTypeCreation=*/true);
10947 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000010948 InjectedClassName->setImplicit();
10949 InjectedClassName->setAccess(AS_public);
10950 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
10951 InjectedClassName->setDescribedClassTemplate(Template);
10952 PushOnScopeChains(InjectedClassName, S);
10953 assert(InjectedClassName->isInjectedClassName() &&
10954 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000010955}
10956
John McCalld226f652010-08-21 09:40:31 +000010957void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000010958 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010959 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000010960 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000010961 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000010962
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000010963 // Make sure we "complete" the definition even it is invalid.
10964 if (Tag->isBeingDefined()) {
10965 assert(Tag->isInvalidDecl() && "We should already have completed it");
10966 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
10967 RD->completeDefinition();
10968 }
10969
Douglas Gregor72de6672009-01-08 20:45:30 +000010970 if (isa<CXXRecordDecl>(Tag))
10971 FieldCollector->FinishClass();
10972
10973 // Exit this scope of this tag's definition.
10974 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000010975
10976 if (getCurLexicalContext()->isObjCContainer() &&
10977 Tag->getDeclContext()->isFileContext())
10978 Tag->setTopLevelDeclInObjCContainer();
10979
Douglas Gregor72de6672009-01-08 20:45:30 +000010980 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000010981 if (!Tag->isInvalidDecl())
10982 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000010983}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000010984
Fariborz Jahanian10af8792011-08-29 17:33:12 +000010985void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000010986 // Exit this scope of this interface definition.
10987 PopDeclContext();
10988}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000010989
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000010990void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000010991 assert(DC == CurContext && "Mismatch of container contexts");
10992 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000010993 ActOnObjCContainerFinishDefinition();
10994}
10995
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000010996void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
10997 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000010998 OriginalLexicalContext = 0;
10999}
11000
John McCalld226f652010-08-21 09:40:31 +000011001void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011002 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011003 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011004 Tag->setInvalidDecl();
11005
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011006 // Make sure we "complete" the definition even it is invalid.
11007 if (Tag->isBeingDefined()) {
11008 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11009 RD->completeDefinition();
11010 }
11011
John McCalla8cab012010-03-17 19:25:57 +000011012 // We're undoing ActOnTagStartDefinition here, not
11013 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11014 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011015
11016 PopDeclContext();
11017}
11018
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011019// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011020ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11021 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011022 QualType FieldTy, bool IsMsStruct,
11023 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011024 // Default to true; that shouldn't confuse checks for emptiness
11025 if (ZeroWidth)
11026 *ZeroWidth = true;
11027
Chris Lattner24793662009-03-05 22:45:59 +000011028 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011029 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011030 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011031 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011032 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011033 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011034 if (FieldName)
11035 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11036 << FieldName << FieldTy << BitWidth->getSourceRange();
11037 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11038 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011039 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11040 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011041 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011042
11043 // If the bit-width is type- or value-dependent, don't try to check
11044 // it now.
11045 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011046 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011047
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011048 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011049 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11050 if (ICE.isInvalid())
11051 return ICE;
11052 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011053
Eli Friedman1d954f62009-08-15 21:55:26 +000011054 if (Value != 0 && ZeroWidth)
11055 *ZeroWidth = false;
11056
Chris Lattnercd087072008-12-12 04:56:04 +000011057 // Zero-width bitfield is ok for anonymous field.
11058 if (Value == 0 && FieldName)
11059 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011060
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011061 if (Value.isSigned() && Value.isNegative()) {
11062 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011063 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011064 << FieldName << Value.toString(10);
11065 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11066 << Value.toString(10);
11067 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011068
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011069 if (!FieldTy->isDependentType()) {
11070 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011071 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011072 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011073 if (FieldName)
11074 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11075 << FieldName << (unsigned)Value.getZExtValue()
11076 << (unsigned)TypeSize;
11077
11078 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11079 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11080 }
11081
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011082 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011083 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11084 << FieldName << (unsigned)Value.getZExtValue()
11085 << (unsigned)TypeSize;
11086 else
11087 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11088 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011089 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011090 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011091
Richard Smith282e7e62012-02-04 09:53:13 +000011092 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011093}
11094
Richard Smith7a614d82011-06-11 17:19:42 +000011095/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011096/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011097Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011098 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011099 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011100 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011101 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011102 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011103}
11104
11105/// HandleField - Analyze a field of a C struct or a C++ data member.
11106///
11107FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11108 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011109 Declarator &D, Expr *BitWidth,
11110 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011111 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011112 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011113 SourceLocation Loc = DeclStart;
11114 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011115
John McCallbf1a0282010-06-04 23:28:52 +000011116 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11117 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011118 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011119 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011120
Douglas Gregore1862692010-12-15 23:18:36 +000011121 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11122 UPPC_DataMemberType)) {
11123 D.setInvalidType();
11124 T = Context.IntTy;
11125 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11126 }
11127 }
11128
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011129 // TR 18037 does not allow fields to be declared with address spaces.
11130 if (T.getQualifiers().hasAddressSpace()) {
11131 Diag(Loc, diag::err_field_with_address_space);
11132 D.setInvalidType();
11133 }
11134
Guy Benyeie6b9d802013-01-20 12:31:11 +000011135 // OpenCL 1.2 spec, s6.9 r:
11136 // The event type cannot be used to declare a structure or union field.
11137 if (LangOpts.OpenCL && T->isEventT()) {
11138 Diag(Loc, diag::err_event_t_struct_field);
11139 D.setInvalidType();
11140 }
11141
Richard Smithc7f81162013-03-18 22:52:47 +000011142 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011143
Richard Smithec642442013-04-12 22:46:28 +000011144 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11145 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11146 diag::err_invalid_thread)
11147 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011148
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011149 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011150 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011151 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11152 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011153 switch (Previous.getResultKind()) {
11154 case LookupResult::Found:
11155 case LookupResult::FoundUnresolvedValue:
11156 PrevDecl = Previous.getAsSingle<NamedDecl>();
11157 break;
11158
11159 case LookupResult::FoundOverloaded:
11160 PrevDecl = Previous.getRepresentativeDecl();
11161 break;
11162
11163 case LookupResult::NotFound:
11164 case LookupResult::NotFoundInCurrentInstantiation:
11165 case LookupResult::Ambiguous:
11166 break;
11167 }
11168 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011169
11170 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11171 // Maybe we will complain about the shadowed template parameter.
11172 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11173 // Just pretend that we didn't see the previous declaration.
11174 PrevDecl = 0;
11175 }
11176
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011177 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11178 PrevDecl = 0;
11179
Steve Naroffea218b82009-07-14 14:58:18 +000011180 bool Mutable
11181 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011182 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011183 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011184 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011185 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011186
11187 if (NewFD->isInvalidDecl())
11188 Record->setInvalidDecl();
11189
Douglas Gregor591dc842011-09-12 16:11:24 +000011190 if (D.getDeclSpec().isModulePrivateSpecified())
11191 NewFD->setModulePrivate();
11192
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011193 if (NewFD->isInvalidDecl() && PrevDecl) {
11194 // Don't introduce NewFD into scope; there's already something
11195 // with the same name in the same scope.
11196 } else if (II) {
11197 PushOnScopeChains(NewFD, S);
11198 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011199 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011200
11201 return NewFD;
11202}
11203
11204/// \brief Build a new FieldDecl and check its well-formedness.
11205///
11206/// This routine builds a new FieldDecl given the fields name, type,
11207/// record, etc. \p PrevDecl should refer to any previous declaration
11208/// with the same name and in the same scope as the field to be
11209/// created.
11210///
11211/// \returns a new FieldDecl.
11212///
Mike Stump1eb44332009-09-09 15:08:12 +000011213/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011214FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011215 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011216 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011217 bool Mutable, Expr *BitWidth,
11218 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011219 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011220 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011221 Declarator *D) {
11222 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011223 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011224 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011225
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011226 // If we receive a broken type, recover by assuming 'int' and
11227 // marking this declaration as invalid.
11228 if (T.isNull()) {
11229 InvalidDecl = true;
11230 T = Context.IntTy;
11231 }
11232
Eli Friedman721e77d2009-12-07 00:22:08 +000011233 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011234 if (!EltTy->isDependentType()) {
11235 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11236 // Fields of incomplete type force their record to be invalid.
11237 Record->setInvalidDecl();
11238 InvalidDecl = true;
11239 } else {
11240 NamedDecl *Def;
11241 EltTy->isIncompleteType(&Def);
11242 if (Def && Def->isInvalidDecl()) {
11243 Record->setInvalidDecl();
11244 InvalidDecl = true;
11245 }
11246 }
John McCall2d7d2d92010-08-16 23:42:35 +000011247 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011248
Joey Gouly617bb312013-01-17 17:35:00 +000011249 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11250 if (BitWidth && getLangOpts().OpenCL) {
11251 Diag(Loc, diag::err_opencl_bitfields);
11252 InvalidDecl = true;
11253 }
11254
Reid Spencer5f016e22007-07-11 17:01:13 +000011255 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11256 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011257 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011258 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011259 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011260
11261 TypeSourceInfo *FixedTInfo =
11262 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11263 SizeIsNegative,
11264 Oversized);
11265 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011266 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011267 TInfo = FixedTInfo;
11268 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011269 } else {
11270 if (SizeIsNegative)
11271 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011272 else if (Oversized.getBoolValue())
11273 Diag(Loc, diag::err_array_too_large)
11274 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011275 else
11276 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011277 InvalidDecl = true;
11278 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011279 }
Mike Stump1eb44332009-09-09 15:08:12 +000011280
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011281 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011282 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11283 diag::err_abstract_type_in_decl,
11284 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011285 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011286
Eli Friedman1d954f62009-08-15 21:55:26 +000011287 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011288 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011289 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011290 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11291 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011292 if (!BitWidth) {
11293 InvalidDecl = true;
11294 BitWidth = 0;
11295 ZeroWidth = false;
11296 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011297 }
Mike Stump1eb44332009-09-09 15:08:12 +000011298
John McCall4bde1e12010-06-04 08:34:12 +000011299 // Check that 'mutable' is consistent with the type of the declaration.
11300 if (!InvalidDecl && Mutable) {
11301 unsigned DiagID = 0;
11302 if (T->isReferenceType())
11303 DiagID = diag::err_mutable_reference;
11304 else if (T.isConstQualified())
11305 DiagID = diag::err_mutable_const;
11306
11307 if (DiagID) {
11308 SourceLocation ErrLoc = Loc;
11309 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11310 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11311 Diag(ErrLoc, DiagID);
11312 Mutable = false;
11313 InvalidDecl = true;
11314 }
11315 }
11316
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011317 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011318 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011319 if (InvalidDecl)
11320 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011321
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011322 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11323 Diag(Loc, diag::err_duplicate_member) << II;
11324 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11325 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011326 }
11327
David Blaikie4e4d0842012-03-11 07:00:24 +000011328 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011329 if (Record->isUnion()) {
11330 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11331 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11332 if (RDecl->getDefinition()) {
11333 // C++ [class.union]p1: An object of a class with a non-trivial
11334 // constructor, a non-trivial copy constructor, a non-trivial
11335 // destructor, or a non-trivial copy assignment operator
11336 // cannot be a member of a union, nor can an array of such
11337 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011338 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011339 NewFD->setInvalidDecl();
11340 }
11341 }
11342
11343 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011344 // the program is ill-formed, except when compiling with MSVC extensions
11345 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011346 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011347 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11348 diag::ext_union_member_of_reference_type :
11349 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011350 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011351 if (!getLangOpts().MicrosoftExt)
11352 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011353 }
11354 }
11355 }
11356
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011357 // FIXME: We need to pass in the attributes given an AST
11358 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011359 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011360 // FIXME: The current scope is almost... but not entirely... correct here.
11361 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011362
Richard Smithbe507b62013-02-01 08:12:08 +000011363 if (NewFD->hasAttrs())
11364 CheckAlignasUnderalignment(NewFD);
11365 }
11366
John McCallf85e1932011-06-15 23:02:42 +000011367 // In auto-retain/release, infer strong retension for fields of
11368 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011369 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011370 NewFD->setInvalidDecl();
11371
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011372 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011373 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011374
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011375 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011376 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011377}
11378
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011379bool Sema::CheckNontrivialField(FieldDecl *FD) {
11380 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011381 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011382
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011383 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11384 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011385
11386 QualType EltTy = Context.getBaseElementType(FD->getType());
11387 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011388 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011389 if (RDecl->getDefinition()) {
11390 // We check for copy constructors before constructors
11391 // because otherwise we'll never get complaints about
11392 // copy constructors.
11393
11394 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011395 // We're required to check for any non-trivial constructors. Since the
11396 // implicit default constructor is suppressed if there are any
11397 // user-declared constructors, we just need to check that there is a
11398 // trivial default constructor and a trivial copy constructor. (We don't
11399 // worry about move constructors here, since this is a C++98 check.)
11400 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011401 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011402 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011403 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011404 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011405 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011406 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011407 member = CXXDestructor;
11408
11409 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011410 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011411 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011412 // Objective-C++ ARC: it is an error to have a non-trivial field of
11413 // a union. However, system headers in Objective-C programs
11414 // occasionally have Objective-C lifetime objects within unions,
11415 // and rather than cause the program to fail, we make those
11416 // members unavailable.
11417 SourceLocation Loc = FD->getLocation();
11418 if (getSourceManager().isInSystemHeader(Loc)) {
11419 if (!FD->hasAttr<UnavailableAttr>())
11420 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011421 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011422 return false;
11423 }
11424 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011425
Richard Smith80ad52f2013-01-02 11:42:31 +000011426 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011427 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11428 diag::err_illegal_union_or_anon_struct_member)
11429 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011430 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011431 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011432 }
11433 }
11434 }
Richard Smithac713512012-12-08 02:53:02 +000011435
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011436 return false;
11437}
11438
Mike Stump1eb44332009-09-09 15:08:12 +000011439/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011440/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011441static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011442TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011443 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011444 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011445 case tok::objc_private: return ObjCIvarDecl::Private;
11446 case tok::objc_public: return ObjCIvarDecl::Public;
11447 case tok::objc_protected: return ObjCIvarDecl::Protected;
11448 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011449 }
11450}
11451
Mike Stump1eb44332009-09-09 15:08:12 +000011452/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011453/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011454Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011455 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011456 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011457 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011458
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011459 IdentifierInfo *II = D.getIdentifier();
11460 Expr *BitWidth = (Expr*)BitfieldWidth;
11461 SourceLocation Loc = DeclStart;
11462 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011463
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011464 // FIXME: Unnamed fields can be handled in various different ways, for
11465 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011466
John McCallbf1a0282010-06-04 23:28:52 +000011467 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11468 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011469
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011470 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011471 // 6.7.2.1p3, 6.7.2.1p4
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011472 BitWidth =
11473 VerifyBitField(Loc, II, T, /*IsMsStruct=*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011474 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011475 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011476 } else {
11477 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011478
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011479 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011480
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011481 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011482 if (T->isReferenceType()) {
11483 Diag(Loc, diag::err_ivar_reference_type);
11484 D.setInvalidType();
11485 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011486 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11487 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011488 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011489 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011490 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011491 }
Mike Stump1eb44332009-09-09 15:08:12 +000011492
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011493 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011494 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011495 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11496 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011497 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011498 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011499 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11500 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011501 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011502 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011503 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011504 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011505 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011506 EnclosingContext = IMPDecl->getClassInterface();
11507 assert(EnclosingContext && "Implementation has no class interface!");
11508 }
11509 else
11510 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011511 } else {
11512 if (ObjCCategoryDecl *CDecl =
11513 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011514 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011515 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011516 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011517 }
11518 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011519 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011520 }
Mike Stump1eb44332009-09-09 15:08:12 +000011521
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011522 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011523 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11524 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011525 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011526
Douglas Gregor72de6672009-01-08 20:45:30 +000011527 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011528 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011529 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011530 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011531 && !isa<TagDecl>(PrevDecl)) {
11532 Diag(Loc, diag::err_duplicate_member) << II;
11533 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11534 NewID->setInvalidDecl();
11535 }
11536 }
11537
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011538 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011539 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011540
Chris Lattnereaaebc72009-04-25 08:06:05 +000011541 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011542 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011543
John McCallf85e1932011-06-15 23:02:42 +000011544 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011545 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011546 NewID->setInvalidDecl();
11547
Douglas Gregor591dc842011-09-12 16:11:24 +000011548 if (D.getDeclSpec().isModulePrivateSpecified())
11549 NewID->setModulePrivate();
11550
Douglas Gregor72de6672009-01-08 20:45:30 +000011551 if (II) {
11552 // FIXME: When interfaces are DeclContexts, we'll need to add
11553 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011554 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011555 IdResolver.AddDecl(NewID);
11556 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011557
John McCall260611a2012-06-20 06:18:46 +000011558 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011559 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011560 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011561
John McCalld226f652010-08-21 09:40:31 +000011562 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011563}
11564
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011565/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011566/// class and class extensions. For every class \@interface and class
11567/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011568/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011569void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011570 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011571 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011572 return;
11573
11574 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11575 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11576
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011577 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011578 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011579 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011580 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011581 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011582 if (!CD->IsClassExtension())
11583 return;
11584 }
11585 // No need to add this to end of @implementation.
11586 else
11587 return;
11588 }
11589 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011590 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11591 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011592
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011593 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011594 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011595 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011596 Context.getTrivialTypeSourceInfo(Context.CharTy,
11597 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011598 ObjCIvarDecl::Private, BW,
11599 true);
11600 AllIvarDecls.push_back(Ivar);
11601}
11602
Robert Wilhelm834c0582013-08-09 18:02:13 +000011603void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11604 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11605 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011606 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011607
Eric Christopher6dba4a12012-07-19 22:22:51 +000011608 // If this is an Objective-C @implementation or category and we have
11609 // new fields here we should reset the layout of the interface since
11610 // it will now change.
11611 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11612 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11613 switch (DC->getKind()) {
11614 default: break;
11615 case Decl::ObjCCategory:
11616 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11617 break;
11618 case Decl::ObjCImplementation:
11619 Context.
11620 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11621 break;
11622 }
11623 }
11624
Eli Friedman11e70d72012-02-07 05:00:47 +000011625 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11626
11627 // Start counting up the number of named members; make sure to include
11628 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011629 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011630 if (Record) {
11631 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11632 e = Record->decls_end(); i != e; i++) {
11633 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11634 if (IFD->getDeclName())
11635 ++NumNamedMembers;
11636 }
11637 }
11638
11639 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011640 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011641
John McCallf85e1932011-06-15 23:02:42 +000011642 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011643 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011644 i != end; ++i) {
11645 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011646
Reid Spencer5f016e22007-07-11 17:01:13 +000011647 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011648 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011649
Douglas Gregor72de6672009-01-08 20:45:30 +000011650 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011651 // Remember all fields written by the user.
11652 RecFields.push_back(FD);
11653 }
Mike Stump1eb44332009-09-09 15:08:12 +000011654
Chris Lattner24793662009-03-05 22:45:59 +000011655 // If the field is already invalid for some reason, don't emit more
11656 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011657 if (FD->isInvalidDecl()) {
11658 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011659 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011660 }
Mike Stump1eb44332009-09-09 15:08:12 +000011661
Douglas Gregore7450f52009-03-24 19:52:54 +000011662 // C99 6.7.2.1p2:
11663 // A structure or union shall not contain a member with
11664 // incomplete or function type (hence, a structure shall not
11665 // contain an instance of itself, but may contain a pointer to
11666 // an instance of itself), except that the last member of a
11667 // structure with more than one named member may have incomplete
11668 // array type; such a structure (and any union containing,
11669 // possibly recursively, a member that is such a structure)
11670 // shall not be a member of a structure or an element of an
11671 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011672 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011673 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011674 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011675 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011676 FD->setInvalidDecl();
11677 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011678 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011679 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011680 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011681 ((getLangOpts().MicrosoftExt ||
11682 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011683 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011684 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011685 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011686 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011687 // as the sole element of a struct/class.
David Blaikie4e4d0842012-03-11 07:00:24 +000011688 if (getLangOpts().MicrosoftExt) {
Francois Pichet09246182010-09-15 00:14:08 +000011689 if (Record->isUnion())
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011690 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichet09246182010-09-15 00:14:08 +000011691 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +000011692 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011693 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichet09246182010-09-15 00:14:08 +000011694 << FD->getDeclName() << Record->getTagKind();
David Blaikie4e4d0842012-03-11 07:00:24 +000011695 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011696 if (Record->isUnion())
11697 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11698 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +000011699 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011700 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
11701 << FD->getDeclName() << Record->getTagKind();
David Chisnall0961a012012-03-16 12:15:37 +000011702 } else if (!getLangOpts().C99) {
11703 if (Record->isUnion())
11704 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11705 << FD->getDeclName();
11706 else
11707 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11708 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011709 } else if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011710 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011711 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011712 FD->setInvalidDecl();
11713 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011714 continue;
11715 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011716 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011717 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011718 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011719 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011720 FD->setInvalidDecl();
11721 EnclosingDecl->setInvalidDecl();
11722 continue;
11723 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011724 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011725 if (Record)
11726 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011727 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011728 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011729 diag::err_field_incomplete)) {
11730 // Incomplete type
11731 FD->setInvalidDecl();
11732 EnclosingDecl->setInvalidDecl();
11733 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011734 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011735 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11736 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011737 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011738 Record->setHasFlexibleArrayMember(true);
11739 } else {
11740 // If this is a struct/class and this is not the last element, reject
11741 // it. Note that GCC supports variable sized arrays in the middle of
11742 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011743 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011744 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011745 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011746 else {
11747 // We support flexible arrays at the end of structs in
11748 // other structs as an extension.
11749 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11750 << FD->getDeclName();
11751 if (Record)
11752 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011753 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011754 }
11755 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011756 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11757 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11758 diag::err_abstract_type_in_decl,
11759 AbstractIvarType)) {
11760 // Ivars can not have abstract class types
11761 FD->setInvalidDecl();
11762 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011763 if (Record && FDTTy->getDecl()->hasObjectMember())
11764 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011765 if (Record && FDTTy->getDecl()->hasVolatileMember())
11766 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011767 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011768 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011769 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11770 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11771 QualType T = Context.getObjCObjectPointerType(FD->getType());
11772 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011773 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11774 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11775 // It's an error in ARC if a field has lifetime.
11776 // We don't want to report this in a system header, though,
11777 // so we just make the field unavailable.
11778 // FIXME: that's really not sufficient; we need to make the type
11779 // itself invalid to, say, initialize or copy.
11780 QualType T = FD->getType();
11781 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11782 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11783 SourceLocation loc = FD->getLocation();
11784 if (getSourceManager().isInSystemHeader(loc)) {
11785 if (!FD->hasAttr<UnavailableAttr>()) {
11786 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11787 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011788 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011789 } else {
11790 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011791 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011792 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011793 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011794 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011795 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011796 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011797 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011798 if (FD->getType()->isObjCObjectPointerType() ||
11799 FD->getType().isObjCGCStrong())
11800 Record->setHasObjectMember(true);
11801 else if (Context.getAsArrayType(FD->getType())) {
11802 QualType BaseType = Context.getBaseElementType(FD->getType());
11803 if (BaseType->isRecordType() &&
11804 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011805 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011806 else if (BaseType->isObjCObjectPointerType() ||
11807 BaseType.isObjCGCStrong())
11808 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011809 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011810 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011811 if (Record && FD->getType().isVolatileQualified())
11812 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011813 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000011814 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000011815 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000011816 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011817
Reid Spencer5f016e22007-07-11 17:01:13 +000011818 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000011819 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011820 bool Completed = false;
11821 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11822 if (!CXXRecord->isInvalidDecl()) {
11823 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011824 for (CXXRecordDecl::conversion_iterator
11825 I = CXXRecord->conversion_begin(),
11826 E = CXXRecord->conversion_end(); I != E; ++I)
11827 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011828
11829 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000011830 if (CXXRecord->hasUserDeclaredDestructor()) {
11831 // Adjust user-defined destructor exception spec.
11832 if (getLangOpts().CPlusPlus11)
11833 AdjustDestructorExceptionSpec(CXXRecord,
11834 CXXRecord->getDestructor());
11835
11836 // The Microsoft ABI requires that we perform the destructor body
11837 // checks (i.e. operator delete() lookup) at every declaration, as
11838 // any translation unit may need to emit a deleting destructor.
11839 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11840 CheckDestructor(CXXRecord->getDestructor());
11841 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000011842
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011843 // Add any implicitly-declared members to this class.
11844 AddImplicitlyDeclaredMembersToClass(CXXRecord);
11845
11846 // If we have virtual base classes, we may end up finding multiple
11847 // final overriders for a given virtual function. Check for this
11848 // problem now.
11849 if (CXXRecord->getNumVBases()) {
11850 CXXFinalOverriderMap FinalOverriders;
11851 CXXRecord->getFinalOverriders(FinalOverriders);
11852
11853 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
11854 MEnd = FinalOverriders.end();
11855 M != MEnd; ++M) {
11856 for (OverridingMethods::iterator SO = M->second.begin(),
11857 SOEnd = M->second.end();
11858 SO != SOEnd; ++SO) {
11859 assert(SO->second.size() > 0 &&
11860 "Virtual function without overridding functions?");
11861 if (SO->second.size() == 1)
11862 continue;
11863
11864 // C++ [class.virtual]p2:
11865 // In a derived class, if a virtual member function of a base
11866 // class subobject has more than one final overrider the
11867 // program is ill-formed.
11868 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000011869 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011870 Diag(M->first->getLocation(),
11871 diag::note_overridden_virtual_function);
11872 for (OverridingMethods::overriding_iterator
11873 OM = SO->second.begin(),
11874 OMEnd = SO->second.end();
11875 OM != OMEnd; ++OM)
11876 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000011877 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011878
11879 Record->setInvalidDecl();
11880 }
11881 }
11882 CXXRecord->completeDefinition(&FinalOverriders);
11883 Completed = true;
11884 }
11885 }
11886 }
11887 }
11888
11889 if (!Completed)
11890 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000011891
Richard Smithbe507b62013-02-01 08:12:08 +000011892 if (Record->hasAttrs())
11893 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000011894
11895 // Check if the structure/union declaration is a language extension.
11896 if (!getLangOpts().CPlusPlus) {
11897 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000011898 bool IsEmpty = true;
11899 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000011900 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000011901 E = Record->field_end();
11902 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
11903 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000011904 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000011905 if (I->getBitWidthValue(Context) > 0)
11906 ZeroSize = false;
11907 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000011908 ++NonBitFields;
11909 QualType FieldType = I->getType();
11910 if (FieldType->isIncompleteType() ||
11911 !Context.getTypeSizeInChars(FieldType).isZero())
11912 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000011913 }
11914 }
11915
11916 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
11917 // C++.
Serge Pavlov0dcea352013-06-17 17:18:51 +000011918 if (ZeroSize)
11919 Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
11920 << Record->isUnion() << (NonBitFields > 1);
Serge Pavlov122e6012013-06-08 13:29:58 +000011921
11922 // Structs without named members are extension in C (C99 6.7.2.1p7), but
11923 // are accepted by GCC.
Serge Pavlov0dcea352013-06-17 17:18:51 +000011924 if (NonBitFields == 0) {
11925 if (IsEmpty)
Serge Pavlov122e6012013-06-08 13:29:58 +000011926 Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
11927 else
11928 Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
11929 }
11930 }
Chris Lattnere1e79852008-02-06 00:51:33 +000011931 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000011932 ObjCIvarDecl **ClsFields =
11933 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000011934 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000011935 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011936 // Add ivar's to class's DeclContext.
11937 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
11938 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011939 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011940 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000011941 // Must enforce the rule that ivars in the base classes may not be
11942 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000011943 if (ID->getSuperClass())
11944 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000011945 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000011946 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011947 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011948 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
11949 // Ivar declared in @implementation never belongs to the implementation.
11950 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000011951 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000011952 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000011953 IMPDecl->setIvarLBraceLoc(LBrac);
11954 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000011955 } else if (ObjCCategoryDecl *CDecl =
11956 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011957 // case of ivars in class extension; all other cases have been
11958 // reported as errors elsewhere.
11959 // FIXME. Class extension does not have a LocEnd field.
11960 // CDecl->setLocEnd(RBrac);
11961 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000011962 // Diagnose redeclaration of private ivars.
11963 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011964 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000011965 if (IDecl) {
11966 if (const ObjCIvarDecl *ClsIvar =
11967 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
11968 Diag(ClsFields[i]->getLocation(),
11969 diag::err_duplicate_ivar_declaration);
11970 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
11971 continue;
11972 }
Douglas Gregord3297242013-01-16 23:00:23 +000011973 for (ObjCInterfaceDecl::known_extensions_iterator
11974 Ext = IDecl->known_extensions_begin(),
11975 ExtEnd = IDecl->known_extensions_end();
11976 Ext != ExtEnd; ++Ext) {
11977 if (const ObjCIvarDecl *ClsExtIvar
11978 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000011979 Diag(ClsFields[i]->getLocation(),
11980 diag::err_duplicate_ivar_declaration);
11981 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
11982 continue;
11983 }
11984 }
11985 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011986 ClsFields[i]->setLexicalDeclContext(CDecl);
11987 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000011988 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000011989 CDecl->setIvarLBraceLoc(LBrac);
11990 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000011991 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000011992 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000011993
11994 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011995 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000011996}
11997
Douglas Gregor677e4fe2010-02-01 23:36:03 +000011998/// \brief Determine whether the given integral value is representable within
11999/// the given type T.
12000static bool isRepresentableIntegerValue(ASTContext &Context,
12001 llvm::APSInt &Value,
12002 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012003 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012004 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012005
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012006 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012007 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012008 --BitWidth;
12009 return Value.getActiveBits() <= BitWidth;
12010 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012011 return Value.getMinSignedBits() <= BitWidth;
12012}
12013
12014// \brief Given an integral type, return the next larger integral type
12015// (or a NULL type of no such type exists).
12016static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12017 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12018 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012019 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012020 const unsigned NumTypes = 4;
12021 QualType SignedIntegralTypes[NumTypes] = {
12022 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12023 };
12024 QualType UnsignedIntegralTypes[NumTypes] = {
12025 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12026 Context.UnsignedLongLongTy
12027 };
12028
12029 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012030 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12031 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012032 for (unsigned I = 0; I != NumTypes; ++I)
12033 if (Context.getTypeSize(Types[I]) > BitWidth)
12034 return Types[I];
12035
12036 return QualType();
12037}
12038
Douglas Gregor879fd492009-03-17 19:05:46 +000012039EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12040 EnumConstantDecl *LastEnumConst,
12041 SourceLocation IdLoc,
12042 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012043 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012044 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012045 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012046 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012047
12048 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12049 Val = 0;
12050
Eli Friedman19efa3e2011-12-06 00:10:34 +000012051 if (Val)
12052 Val = DefaultLvalueConversion(Val).take();
12053
Douglas Gregor4912c342009-11-06 00:03:12 +000012054 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012055 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012056 EltTy = Context.DependentTy;
12057 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012058 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012059 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012060 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012061 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12062 // constant-expression in the enumerator-definition shall be a converted
12063 // constant expression of the underlying type.
12064 EltTy = Enum->getIntegerType();
12065 ExprResult Converted =
12066 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12067 CCEK_Enumerator);
12068 if (Converted.isInvalid())
12069 Val = 0;
12070 else
12071 Val = Converted.take();
12072 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012073 !(Val = VerifyIntegerConstantExpression(Val,
12074 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012075 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012076 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012077 if (Enum->isFixed()) {
12078 EltTy = Enum->getIntegerType();
12079
Richard Smith8ef7b202012-01-18 23:55:52 +000012080 // In Obj-C and Microsoft mode, require the enumeration value to be
12081 // representable in the underlying type of the enumeration. In C++11,
12082 // we perform a non-narrowing conversion as part of converted constant
12083 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012084 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012085 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012086 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012087 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012088 } else
12089 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012090 } else
John Wiegley429bb272011-04-08 18:41:53 +000012091 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012092 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012093 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012094 // If the underlying type is not fixed, the type of each enumerator
12095 // is the type of its initializing value:
12096 // - If an initializer is specified for an enumerator, the
12097 // initializing value has the same type as the expression.
12098 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012099 } else {
12100 // C99 6.7.2.2p2:
12101 // The expression that defines the value of an enumeration constant
12102 // shall be an integer constant expression that has a value
12103 // representable as an int.
12104
12105 // Complain if the value is not representable in an int.
12106 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12107 Diag(IdLoc, diag::ext_enum_value_not_int)
12108 << EnumVal.toString(10) << Val->getSourceRange()
12109 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12110 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12111 // Force the type of the expression to 'int'.
12112 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12113 }
12114 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012115 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012116 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012117 }
12118 }
Mike Stump1eb44332009-09-09 15:08:12 +000012119
Douglas Gregor879fd492009-03-17 19:05:46 +000012120 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012121 if (Enum->isDependentType())
12122 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012123 else if (!LastEnumConst) {
12124 // C++0x [dcl.enum]p5:
12125 // If the underlying type is not fixed, the type of each enumerator
12126 // is the type of its initializing value:
12127 // - If no initializer is specified for the first enumerator, the
12128 // initializing value has an unspecified integral type.
12129 //
12130 // GCC uses 'int' for its unspecified integral type, as does
12131 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012132 if (Enum->isFixed()) {
12133 EltTy = Enum->getIntegerType();
12134 }
12135 else {
12136 EltTy = Context.IntTy;
12137 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012138 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012139 // Assign the last value + 1.
12140 EnumVal = LastEnumConst->getInitVal();
12141 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012142 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012143
12144 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012145 if (EnumVal < LastEnumConst->getInitVal()) {
12146 // C++0x [dcl.enum]p5:
12147 // If the underlying type is not fixed, the type of each enumerator
12148 // is the type of its initializing value:
12149 //
12150 // - Otherwise the type of the initializing value is the same as
12151 // the type of the initializing value of the preceding enumerator
12152 // unless the incremented value is not representable in that type,
12153 // in which case the type is an unspecified integral type
12154 // sufficient to contain the incremented value. If no such type
12155 // exists, the program is ill-formed.
12156 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012157 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012158 // There is no integral type larger enough to represent this
12159 // value. Complain, then allow the value to wrap around.
12160 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012161 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012162 ++EnumVal;
12163 if (Enum->isFixed())
12164 // When the underlying type is fixed, this is ill-formed.
12165 Diag(IdLoc, diag::err_enumerator_wrapped)
12166 << EnumVal.toString(10)
12167 << EltTy;
12168 else
12169 Diag(IdLoc, diag::warn_enumerator_too_large)
12170 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012171 } else {
12172 EltTy = T;
12173 }
12174
12175 // Retrieve the last enumerator's value, extent that type to the
12176 // type that is supposed to be large enough to represent the incremented
12177 // value, then increment.
12178 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012179 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012180 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012181 ++EnumVal;
12182
12183 // If we're not in C++, diagnose the overflow of enumerator values,
12184 // which in C99 means that the enumerator value is not representable in
12185 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12186 // permits enumerator values that are representable in some larger
12187 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012188 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012189 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012190 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012191 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12192 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12193 Diag(IdLoc, diag::ext_enum_value_not_int)
12194 << EnumVal.toString(10) << 1;
12195 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012196 }
12197 }
Mike Stump1eb44332009-09-09 15:08:12 +000012198
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012199 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012200 // Make the enumerator value match the signedness and size of the
12201 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012202 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012203 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012204 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012205
Douglas Gregor879fd492009-03-17 19:05:46 +000012206 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012207 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012208}
12209
12210
John McCall5b629aa2010-10-22 23:36:17 +000012211Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12212 SourceLocation IdLoc, IdentifierInfo *Id,
12213 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012214 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012215 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012216 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012217 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012218
Chris Lattner31e05722007-08-26 06:24:45 +000012219 // The scope passed in may not be a decl scope. Zip up the scope tree until
12220 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012221 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012222
Reid Spencer5f016e22007-07-11 17:01:13 +000012223 // Verify that there isn't already something declared with this name in this
12224 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012225 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012226 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012227 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012228 // Maybe we will complain about the shadowed template parameter.
12229 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12230 // Just pretend that we didn't see the previous declaration.
12231 PrevDecl = 0;
12232 }
12233
12234 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012235 // When in C++, we may get a TagDecl with the same name; in this case the
12236 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012237 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012238 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012239 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012240 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012241 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012242 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012243 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012244 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012245 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012246 }
12247 }
12248
Aaron Ballmanf8167872012-07-19 03:12:23 +000012249 // C++ [class.mem]p15:
12250 // If T is the name of a class, then each of the following shall have a name
12251 // different from T:
12252 // - every enumerator of every member of class T that is an unscoped
12253 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012254 if (CXXRecordDecl *Record
12255 = dyn_cast<CXXRecordDecl>(
12256 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012257 if (!TheEnumDecl->isScoped() &&
12258 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012259 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12260
John McCall5b629aa2010-10-22 23:36:17 +000012261 EnumConstantDecl *New =
12262 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012263
John McCall92f88312010-01-23 00:46:32 +000012264 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012265 // Process attributes.
12266 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12267
12268 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012269 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012270 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012271 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012272
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012273 ActOnDocumentableDecl(New);
12274
John McCalld226f652010-08-21 09:40:31 +000012275 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012276}
12277
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012278// Returns true when the enum initial expression does not trigger the
12279// duplicate enum warning. A few common cases are exempted as follows:
12280// Element2 = Element1
12281// Element2 = Element1 + 1
12282// Element2 = Element1 - 1
12283// Where Element2 and Element1 are from the same enum.
12284static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12285 Expr *InitExpr = ECD->getInitExpr();
12286 if (!InitExpr)
12287 return true;
12288 InitExpr = InitExpr->IgnoreImpCasts();
12289
12290 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12291 if (!BO->isAdditiveOp())
12292 return true;
12293 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12294 if (!IL)
12295 return true;
12296 if (IL->getValue() != 1)
12297 return true;
12298
12299 InitExpr = BO->getLHS();
12300 }
12301
12302 // This checks if the elements are from the same enum.
12303 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12304 if (!DRE)
12305 return true;
12306
12307 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12308 if (!EnumConstant)
12309 return true;
12310
12311 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12312 Enum)
12313 return true;
12314
12315 return false;
12316}
12317
12318struct DupKey {
12319 int64_t val;
12320 bool isTombstoneOrEmptyKey;
12321 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12322 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12323};
12324
12325static DupKey GetDupKey(const llvm::APSInt& Val) {
12326 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12327 false);
12328}
12329
12330struct DenseMapInfoDupKey {
12331 static DupKey getEmptyKey() { return DupKey(0, true); }
12332 static DupKey getTombstoneKey() { return DupKey(1, true); }
12333 static unsigned getHashValue(const DupKey Key) {
12334 return (unsigned)(Key.val * 37);
12335 }
12336 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12337 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12338 LHS.val == RHS.val;
12339 }
12340};
12341
12342// Emits a warning when an element is implicitly set a value that
12343// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012344static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12345 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012346 QualType EnumType) {
12347 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12348 Enum->getLocation()) ==
12349 DiagnosticsEngine::Ignored)
12350 return;
12351 // Avoid anonymous enums
12352 if (!Enum->getIdentifier())
12353 return;
12354
12355 // Only check for small enums.
12356 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12357 return;
12358
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012359 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12360 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012361
12362 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12363 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12364 ValueToVectorMap;
12365
12366 DuplicatesVector DupVector;
12367 ValueToVectorMap EnumMap;
12368
12369 // Populate the EnumMap with all values represented by enum constants without
12370 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012371 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012372 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012373
12374 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12375 // this constant. Skip this enum since it may be ill-formed.
12376 if (!ECD) {
12377 return;
12378 }
12379
12380 if (ECD->getInitExpr())
12381 continue;
12382
12383 DupKey Key = GetDupKey(ECD->getInitVal());
12384 DeclOrVector &Entry = EnumMap[Key];
12385
12386 // First time encountering this value.
12387 if (Entry.isNull())
12388 Entry = ECD;
12389 }
12390
12391 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012392 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012393 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12394 if (!ValidDuplicateEnum(ECD, Enum))
12395 continue;
12396
12397 DupKey Key = GetDupKey(ECD->getInitVal());
12398
12399 DeclOrVector& Entry = EnumMap[Key];
12400 if (Entry.isNull())
12401 continue;
12402
12403 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12404 // Ensure constants are different.
12405 if (D == ECD)
12406 continue;
12407
12408 // Create new vector and push values onto it.
12409 ECDVector *Vec = new ECDVector();
12410 Vec->push_back(D);
12411 Vec->push_back(ECD);
12412
12413 // Update entry to point to the duplicates vector.
12414 Entry = Vec;
12415
12416 // Store the vector somewhere we can consult later for quick emission of
12417 // diagnostics.
12418 DupVector.push_back(Vec);
12419 continue;
12420 }
12421
12422 ECDVector *Vec = Entry.get<ECDVector*>();
12423 // Make sure constants are not added more than once.
12424 if (*Vec->begin() == ECD)
12425 continue;
12426
12427 Vec->push_back(ECD);
12428 }
12429
12430 // Emit diagnostics.
12431 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12432 DupVectorEnd = DupVector.end();
12433 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12434 ECDVector *Vec = *DupVectorIter;
12435 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12436
12437 // Emit warning for one enum constant.
12438 ECDVector::iterator I = Vec->begin();
12439 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12440 << (*I)->getName() << (*I)->getInitVal().toString(10)
12441 << (*I)->getSourceRange();
12442 ++I;
12443
12444 // Emit one note for each of the remaining enum constants with
12445 // the same value.
12446 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12447 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12448 << (*I)->getName() << (*I)->getInitVal().toString(10)
12449 << (*I)->getSourceRange();
12450 delete Vec;
12451 }
12452}
12453
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012454void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012455 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012456 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012457 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012458 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012459 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012460
12461 if (Attr)
12462 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012463
Eli Friedmaned0716b2009-12-11 01:34:50 +000012464 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012465 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012466 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012467 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012468 if (!ECD) continue;
12469
12470 ECD->setType(EnumType);
12471 }
12472
John McCall1b5a6182010-05-06 08:49:23 +000012473 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012474 return;
12475 }
12476
Chris Lattnere37f0be2007-08-28 05:10:31 +000012477 // TODO: If the result value doesn't fit in an int, it must be a long or long
12478 // long value. ISO C does not support this, but GCC does as an extension,
12479 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012480 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12481 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12482 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012483
Chris Lattnerac609682007-08-28 06:15:15 +000012484 // Verify that all the values are okay, compute the size of the values, and
12485 // reverse the list.
12486 unsigned NumNegativeBits = 0;
12487 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012488
Chris Lattnerac609682007-08-28 06:15:15 +000012489 // Keep track of whether all elements have type int.
12490 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012491
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012492 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012493 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012494 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012495 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012496
Chris Lattner211a30e2007-08-28 05:27:00 +000012497 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012498
Chris Lattnerac609682007-08-28 06:15:15 +000012499 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012500 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012501 NumPositiveBits = std::max(NumPositiveBits,
12502 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012503 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012504 NumNegativeBits = std::max(NumNegativeBits,
12505 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012506
Chris Lattnerac609682007-08-28 06:15:15 +000012507 // Keep track of whether every enum element has type int (very commmon).
12508 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012509 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012510 }
Mike Stump1eb44332009-09-09 15:08:12 +000012511
Chris Lattnerac609682007-08-28 06:15:15 +000012512 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012513 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012514 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012515
John McCall842aef82009-12-09 09:09:27 +000012516 // C++0x N3000 [conv.prom]p3:
12517 // An rvalue of an unscoped enumeration type whose underlying
12518 // type is not fixed can be converted to an rvalue of the first
12519 // of the following types that can represent all the values of
12520 // the enumeration: int, unsigned int, long int, unsigned long
12521 // int, long long int, or unsigned long long int.
12522 // C99 6.4.4.3p2:
12523 // An identifier declared as an enumeration constant has type int.
12524 // The C99 rule is modified by a gcc extension
12525 QualType BestPromotionType;
12526
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012527 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012528 // -fshort-enums is the equivalent to specifying the packed attribute on all
12529 // enum definitions.
12530 if (LangOpts.ShortEnums)
12531 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012532
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012533 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012534 BestType = Enum->getIntegerType();
12535 if (BestType->isPromotableIntegerType())
12536 BestPromotionType = Context.getPromotedIntegerType(BestType);
12537 else
12538 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012539 // We don't need to set BestWidth, because BestType is going to be the type
12540 // of the enumerators, but we do anyway because otherwise some compilers
12541 // warn that it might be used uninitialized.
12542 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012543 }
12544 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012545 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012546 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012547 // If it's packed, check also if it fits a char or a short.
12548 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012549 BestType = Context.SignedCharTy;
12550 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012551 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012552 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012553 BestType = Context.ShortTy;
12554 BestWidth = ShortWidth;
12555 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012556 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012557 BestWidth = IntWidth;
12558 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012559 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012560
John McCall842aef82009-12-09 09:09:27 +000012561 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012562 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012563 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012564 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012565
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012566 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012567 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12568 BestType = Context.LongLongTy;
12569 }
12570 }
John McCall842aef82009-12-09 09:09:27 +000012571 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012572 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012573 // If there is no negative value, figure out the smallest type that fits
12574 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012575 // If it's packed, check also if it fits a char or a short.
12576 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012577 BestType = Context.UnsignedCharTy;
12578 BestPromotionType = Context.IntTy;
12579 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012580 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012581 BestType = Context.UnsignedShortTy;
12582 BestPromotionType = Context.IntTy;
12583 BestWidth = ShortWidth;
12584 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012585 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012586 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012587 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012588 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012589 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012590 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012591 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012592 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012593 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012594 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012595 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012596 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012597 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012598 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012599 "How could an initializer get larger than ULL?");
12600 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012601 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012602 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012603 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012604 }
12605 }
Mike Stump1eb44332009-09-09 15:08:12 +000012606
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012607 // Loop over all of the enumerator constants, changing their types to match
12608 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012609 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012610 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012611 if (!ECD) continue; // Already issued a diagnostic.
12612
12613 // Standard C says the enumerators have int type, but we allow, as an
12614 // extension, the enumerators to be larger than int size. If each
12615 // enumerator value fits in an int, type it as an int, otherwise type it the
12616 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12617 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012618
12619 // Determine whether the value fits into an int.
12620 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012621
12622 // If it fits into an integer type, force it. Otherwise force it to match
12623 // the enum decl type.
12624 QualType NewTy;
12625 unsigned NewWidth;
12626 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012627 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012628 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012629 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012630 NewTy = Context.IntTy;
12631 NewWidth = IntWidth;
12632 NewSign = true;
12633 } else if (ECD->getType() == BestType) {
12634 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012635 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012636 // C++ [dcl.enum]p4: Following the closing brace of an
12637 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012638 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012639 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012640 continue;
12641 } else {
12642 NewTy = BestType;
12643 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012644 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012645 }
12646
12647 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012648 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012649 InitVal.setIsSigned(NewSign);
12650 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012651
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012652 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012653 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012654 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012655 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012656 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012657 ECD->getInitExpr(),
12658 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012659 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012660 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012661 // C++ [dcl.enum]p4: Following the closing brace of an
12662 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012663 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012664 ECD->setType(EnumType);
12665 else
12666 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012667 }
Mike Stump1eb44332009-09-09 15:08:12 +000012668
John McCall1b5a6182010-05-06 08:49:23 +000012669 Enum->completeDefinition(BestType, BestPromotionType,
12670 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012671
12672 // If we're declaring a function, ensure this decl isn't forgotten about -
12673 // it needs to go into the function scope.
12674 if (InFunctionDeclarator)
12675 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012676
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012677 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012678
12679 // Now that the enum type is defined, ensure it's not been underaligned.
12680 if (Enum->hasAttrs())
12681 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012682}
12683
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012684Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12685 SourceLocation StartLoc,
12686 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012687 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012688
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012689 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012690 AsmString, StartLoc,
12691 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012692 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012693 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012694}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012695
Douglas Gregor5948ae12012-01-03 18:04:46 +000012696DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12697 SourceLocation ImportLoc,
12698 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012699 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012700 Module::AllVisible,
12701 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012702 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012703 return true;
12704
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012705 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012706 Module *ModCheck = Mod;
12707 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12708 // If we've run out of module parents, just drop the remaining identifiers.
12709 // We need the length to be consistent.
12710 if (!ModCheck)
12711 break;
12712 ModCheck = ModCheck->Parent;
12713
12714 IdentifierLocs.push_back(Path[I].second);
12715 }
12716
12717 ImportDecl *Import = ImportDecl::Create(Context,
12718 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012719 AtLoc.isValid()? AtLoc : ImportLoc,
12720 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012721 Context.getTranslationUnitDecl()->addDecl(Import);
12722 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012723}
12724
Douglas Gregorca2ab452013-01-12 01:29:50 +000012725void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12726 // Create the implicit import declaration.
12727 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12728 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12729 Loc, Mod, Loc);
12730 TU->addDecl(ImportD);
12731 Consumer.HandleImplicitImportDecl(ImportD);
12732
12733 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012734 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12735 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012736}
12737
David Chisnall5f3c1632012-02-18 16:12:34 +000012738void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12739 IdentifierInfo* AliasName,
12740 SourceLocation PragmaLoc,
12741 SourceLocation NameLoc,
12742 SourceLocation AliasNameLoc) {
12743 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12744 LookupOrdinaryName);
12745 AsmLabelAttr *Attr =
12746 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012747
12748 if (PrevDecl)
12749 PrevDecl->addAttr(Attr);
12750 else
12751 (void)ExtnameUndeclaredIdentifiers.insert(
12752 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12753}
12754
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012755void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12756 SourceLocation PragmaLoc,
12757 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012758 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012759
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012760 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012761 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012762 } else {
12763 (void)WeakUndeclaredIdentifiers.insert(
12764 std::pair<IdentifierInfo*,WeakInfo>
12765 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012766 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012767}
12768
12769void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12770 IdentifierInfo* AliasName,
12771 SourceLocation PragmaLoc,
12772 SourceLocation NameLoc,
12773 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012774 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12775 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012776 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012777
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012778 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012779 if (!PrevDecl->hasAttr<AliasAttr>())
12780 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012781 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012782 } else {
12783 (void)WeakUndeclaredIdentifiers.insert(
12784 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012785 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012786}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012787
12788Decl *Sema::getObjCDeclContext() const {
12789 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12790}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012791
12792AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000012793 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012794 return D->getAvailability();
12795}