blob: 28b3aa8013ed21ee4ddbb8292f05cc9585e87165 [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 Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000017#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Douglas Gregor9e876872011-03-01 18:12:44 +000020#include "TypeLocBuilder.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000021#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
John McCall7cd088e2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000026#include "clang/AST/DeclTemplate.h"
Chandler Carrutha7689ef2011-03-27 09:46:56 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000028#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000029#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +000030#include "clang/AST/CharUnits.h"
John McCall19510852010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Douglas Gregora786fdb2009-10-13 23:27:22 +000033#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000034#include "clang/Basic/PartialDiagnostic.h"
Fariborz Jahanian175fb102011-10-03 22:11:57 +000035#include "clang/Sema/DelayedDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000036#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000037#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000038// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000039#include "clang/Lex/Preprocessor.h"
Mike Stump1eb44332009-09-09 15:08:12 +000040#include "clang/Lex/HeaderSearch.h"
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000041#include "clang/Lex/ModuleLoader.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:
63 TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) {
64 WantExpressionKeywords = false;
65 WantCXXNamedCasts = false;
66 WantRemainingKeywords = false;
67 }
68
69 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
70 if (NamedDecl *ND = candidate.getCorrectionDecl())
71 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
72 (AllowInvalidDecl || !ND->isInvalidDecl());
73 else
74 return candidate.isKeyword();
75 }
76
77 private:
78 bool AllowInvalidDecl;
79};
80
81}
82
Douglas Gregord6efafa2009-02-04 19:16:12 +000083/// \brief If the identifier refers to a type name within this scope,
84/// return the declaration of that type.
85///
86/// This routine performs ordinary name lookup of the identifier II
87/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000088/// determine whether the name refers to a type. If so, returns an
89/// opaque pointer (actually a QualType) corresponding to that
90/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000091///
92/// If name lookup results in an ambiguity, this routine will complain
93/// and then return NULL.
John McCallb3d87482010-08-24 05:47:05 +000094ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
95 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +000096 bool isClassName, bool HasTrailingDot,
Douglas Gregor9e876872011-03-01 18:12:44 +000097 ParsedType ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +000098 bool IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +000099 bool WantNontrivialTypeSourceInfo,
100 IdentifierInfo **CorrectedII) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000101 // Determine where we will perform name lookup.
102 DeclContext *LookupCtx = 0;
103 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +0000104 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000105 if (ObjectType->isRecordType())
106 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +0000107 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000108 LookupCtx = computeDeclContext(*SS, false);
109
110 if (!LookupCtx) {
111 if (isDependentScopeSpecifier(*SS)) {
112 // C++ [temp.res]p3:
113 // A qualified-id that refers to a type and in which the
114 // nested-name-specifier depends on a template-parameter (14.6.2)
115 // shall be prefixed by the keyword typename to indicate that the
116 // qualified-id denotes a type, forming an
117 // elaborated-type-specifier (7.1.5.3).
118 //
119 // We therefore do not perform any name lookup if the result would
120 // refer to a member of an unknown specialization.
Richard Smithc5a89a12012-04-02 01:30:27 +0000121 if (!isClassName && !IsCtorOrDtorName)
John McCallb3d87482010-08-24 05:47:05 +0000122 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000123
John McCall33500952010-06-11 00:33:02 +0000124 // We know from the grammar that this name refers to a type,
125 // so build a dependent node to describe the type.
Douglas Gregor9e876872011-03-01 18:12:44 +0000126 if (WantNontrivialTypeSourceInfo)
127 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
128
129 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallb3d87482010-08-24 05:47:05 +0000130 QualType T =
Douglas Gregor9e876872011-03-01 18:12:44 +0000131 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +0000132 II, NameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +0000133
134 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000135 }
136
John McCallb3d87482010-08-24 05:47:05 +0000137 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000138 }
139
John McCall77bb1aa2010-05-01 00:40:08 +0000140 if (!LookupCtx->isDependentContext() &&
141 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000142 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000143 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000144
145 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
146 // lookup for class-names.
147 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
148 LookupOrdinaryName;
149 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000150 if (LookupCtx) {
151 // Perform "qualified" name lookup into the declaration context we
152 // computed, which is either the type of the base of a member access
153 // expression or the declaration context associated with a prior
154 // nested-name-specifier.
155 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000156
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000157 if (ObjectTypePtr && Result.empty()) {
158 // C++ [basic.lookup.classref]p3:
159 // If the unqualified-id is ~type-name, the type-name is looked up
160 // in the context of the entire postfix-expression. If the type T of
161 // the object expression is of a class type C, the type-name is also
162 // looked up in the scope of class C. At least one of the lookups shall
163 // find a name that refers to (possibly cv-qualified) T.
164 LookupName(Result, S);
165 }
166 } else {
167 // Perform unqualified name lookup.
168 LookupName(Result, S);
169 }
170
Chris Lattner22bd9052009-02-16 22:07:16 +0000171 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000172 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000173 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000174 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000175 if (CorrectedII) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000176 TypeNameValidatorCCC Validator(true);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000177 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000178 Kind, S, SS, Validator);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000179 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
180 TemplateTy Template;
181 bool MemberOfUnknownSpecialization;
182 UnqualifiedId TemplateName;
183 TemplateName.setIdentifier(NewII, NameLoc);
184 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
185 CXXScopeSpec NewSS, *NewSSPtr = SS;
186 if (SS && NNS) {
187 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
188 NewSSPtr = &NewSS;
189 }
190 if (Correction && (NNS || NewII != &II) &&
191 // Ignore a correction to a template type as the to-be-corrected
192 // identifier is not a template (typo correction for template names
193 // is handled elsewhere).
David Blaikie4e4d0842012-03-11 07:00:24 +0000194 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000195 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
196 false, Template, MemberOfUnknownSpecialization))) {
197 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
198 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000199 IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000200 WantNontrivialTypeSourceInfo);
201 if (Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000202 std::string CorrectedStr(Correction.getAsString(getLangOpts()));
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000203 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000204 Correction.getQuoted(getLangOpts()));
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000205 Diag(NameLoc, diag::err_unknown_typename_suggest)
206 << Result.getLookupName() << CorrectedQuotedStr
207 << FixItHint::CreateReplacement(SourceRange(NameLoc),
208 CorrectedStr);
209 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
210 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
211 << CorrectedQuotedStr;
212
213 if (SS && NNS)
214 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
215 *CorrectedII = NewII;
216 return Ty;
217 }
218 }
219 }
220 // If typo correction failed or was not performed, fall through
Chris Lattner22bd9052009-02-16 22:07:16 +0000221 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000222 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000223 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000224 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000225
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000226 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000227 // Recover from type-hiding ambiguities by hiding the type. We'll
228 // do the lookup again when looking for an object, and we can
229 // diagnose the error then. If we don't do this, then the error
230 // about hiding the type will be immediately followed by an error
231 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000232 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
233 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000234 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000235 }
John McCall6e247262009-10-10 05:48:19 +0000236
Douglas Gregor31a19b62009-04-01 21:51:26 +0000237 // Look to see if we have a type anywhere in the list of results.
238 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
239 Res != ResEnd; ++Res) {
240 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000241 if (!IIDecl ||
242 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000243 IIDecl->getLocation().getRawEncoding())
244 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000245 }
246 }
247
248 if (!IIDecl) {
249 // None of the entities we found is a type, so there is no way
250 // to even assume that the result is a type. In this case, don't
251 // complain about the ambiguity. The parser will either try to
252 // perform this lookup again (e.g., as an object name), which
253 // will produce the ambiguity, or will complain that it expected
254 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000255 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000256 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000257 }
258
259 // We found a type within the ambiguous lookup; diagnose the
260 // ambiguity and then return that type. This might be the right
261 // answer, or it might not be, but it suppresses any attempt to
262 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000263 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000264
Chris Lattner22bd9052009-02-16 22:07:16 +0000265 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000266 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000267 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000268 }
269
Chris Lattner10ca3372009-10-25 17:16:46 +0000270 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000271
Chris Lattner10ca3372009-10-25 17:16:46 +0000272 QualType T;
273 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000274 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000275
Chris Lattner10ca3372009-10-25 17:16:46 +0000276 if (T.isNull())
277 T = Context.getTypeDeclType(TD);
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000278
279 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
280 // constructor or destructor name (in such a case, the scope specifier
281 // will be attached to the enclosing Expr or Decl node).
282 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor9e876872011-03-01 18:12:44 +0000283 if (WantNontrivialTypeSourceInfo) {
284 // Construct a type with type-source information.
285 TypeLocBuilder Builder;
286 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
287
288 T = getElaboratedType(ETK_None, *SS, T);
289 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +0000290 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor9e876872011-03-01 18:12:44 +0000291 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
292 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
293 } else {
294 T = getElaboratedType(ETK_None, *SS, T);
295 }
296 }
Chris Lattner10ca3372009-10-25 17:16:46 +0000297 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000298 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000299 if (!HasTrailingDot)
300 T = Context.getObjCInterfaceType(IDecl);
301 }
302
303 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000304 // If it's not plausibly a type, suppress diagnostics.
305 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000306 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000307 }
John McCallb3d87482010-08-24 05:47:05 +0000308 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000309}
310
Chris Lattner4c97d762009-04-12 21:49:30 +0000311/// isTagName() - This method is called *for error recovery purposes only*
312/// to determine if the specified name is a valid tag name ("struct foo"). If
313/// so, this returns the TST for the tag corresponding to it (TST_enum,
314/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
315/// where the user forgot to specify the tag.
316DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
317 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000318 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
319 LookupName(R, S, false);
320 R.suppressDiagnostics();
321 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000322 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000323 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000324 case TTK_Struct: return DeclSpec::TST_struct;
325 case TTK_Union: return DeclSpec::TST_union;
326 case TTK_Class: return DeclSpec::TST_class;
327 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000328 }
329 }
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner4c97d762009-04-12 21:49:30 +0000331 return DeclSpec::TST_unspecified;
332}
333
Francois Pichet6943e9b2011-04-13 02:38:49 +0000334/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
335/// if a CXXScopeSpec's type is equal to the type of one of the base classes
336/// then downgrade the missing typename error to a warning.
337/// This is needed for MSVC compatibility; Example:
338/// @code
339/// template<class T> class A {
340/// public:
341/// typedef int TYPE;
342/// };
343/// template<class T> class B : public A<T> {
344/// public:
345/// A<T>::TYPE a; // no typename required because A<T> is a base class.
346/// };
347/// @endcode
Francois Pichetf11dbe92011-10-11 01:50:09 +0000348bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000349 if (CurContext->isRecord()) {
Francois Pichet3441a522011-04-13 02:44:57 +0000350 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000351
352 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
353 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
354 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
355 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
356 return true;
Francois Pichetf11dbe92011-10-11 01:50:09 +0000357 return S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000358 }
Francois Pichetf11dbe92011-10-11 01:50:09 +0000359 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000360}
361
Douglas Gregora786fdb2009-10-13 23:27:22 +0000362bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
363 SourceLocation IILoc,
364 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000365 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000366 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000367 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000368 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000369
Douglas Gregor546be3c2009-12-30 17:04:44 +0000370 // There may have been a typo in the name of the type. Look up typo
371 // results, in case we have something that we can suggest.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000372 TypeNameValidatorCCC Validator(false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000373 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000374 LookupOrdinaryName, S, SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000375 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000376 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
377 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor546be3c2009-12-30 17:04:44 +0000378
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000379 if (Corrected.isKeyword()) {
380 // We corrected to a keyword.
381 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
382 Diag(IILoc, diag::err_unknown_typename_suggest)
383 << &II << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000384 } else {
385 NamedDecl *Result = Corrected.getCorrectionDecl();
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000386 // We found a similarly-named type or interface; suggest that.
387 if (!SS || !SS->isSet())
388 Diag(IILoc, diag::err_unknown_typename_suggest)
389 << &II << CorrectedQuotedStr
390 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
391 else if (DeclContext *DC = computeDeclContext(*SS, false))
392 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
393 << &II << DC << CorrectedQuotedStr << SS->getRange()
394 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
395 else
396 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor546be3c2009-12-30 17:04:44 +0000397
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000398 Diag(Result->getLocation(), diag::note_previous_decl)
399 << CorrectedQuotedStr;
400
401 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
402 false, false, ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000403 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000404 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor546be3c2009-12-30 17:04:44 +0000405 }
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000406 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000407 }
408
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000410 // See if II is a class template that the user forgot to pass arguments to.
411 UnqualifiedId Name;
412 Name.setIdentifier(&II, IILoc);
413 CXXScopeSpec EmptySS;
414 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000415 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000416 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000417 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000418 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000419 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
420 Diag(IILoc, diag::err_template_missing_args) << TplName;
421 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
422 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
423 << TplDecl->getTemplateParameters()->getSourceRange();
424 }
425 return true;
426 }
427 }
428
Douglas Gregora786fdb2009-10-13 23:27:22 +0000429 // FIXME: Should we move the logic that tries to recover from a missing tag
430 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
431
Douglas Gregor546be3c2009-12-30 17:04:44 +0000432 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregora786fdb2009-10-13 23:27:22 +0000433 Diag(IILoc, diag::err_unknown_typename) << &II;
434 else if (DeclContext *DC = computeDeclContext(*SS, false))
435 Diag(IILoc, diag::err_typename_nested_not_found)
436 << &II << DC << SS->getRange();
437 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000438 unsigned DiagID = diag::err_typename_missing;
David Blaikie4e4d0842012-03-11 07:00:24 +0000439 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichetcf320c62011-04-22 08:25:24 +0000440 DiagID = diag::warn_typename_missing;
Francois Pichet6943e9b2011-04-13 02:38:49 +0000441
442 Diag(SS->getRange().getBegin(), DiagID)
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000443 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000444 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000445 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
David Blaikied662a792011-10-19 22:56:21 +0000446 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
447 .get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000448 } else {
449 assert(SS && SS->isInvalid() &&
450 "Invalid scope specifier has already been diagnosed");
451 }
452
453 return true;
454}
Chris Lattner4c97d762009-04-12 21:49:30 +0000455
Douglas Gregor312eadb2011-04-24 05:37:28 +0000456/// \brief Determine whether the given result set contains either a type name
457/// or
458static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000459 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000460 NextToken.is(tok::less);
461
462 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
463 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
464 return true;
465
466 if (CheckTemplate && isa<TemplateDecl>(*I))
467 return true;
468 }
469
470 return false;
471}
472
473Sema::NameClassification Sema::ClassifyName(Scope *S,
474 CXXScopeSpec &SS,
475 IdentifierInfo *&Name,
476 SourceLocation NameLoc,
477 const Token &NextToken) {
478 DeclarationNameInfo NameInfo(Name, NameLoc);
479 ObjCMethodDecl *CurMethod = getCurMethodDecl();
480
481 if (NextToken.is(tok::coloncolon)) {
482 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
483 QualType(), false, SS, 0, false);
484
485 }
486
487 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
488 LookupParsedName(Result, S, &SS, !CurMethod);
489
490 // Perform lookup for Objective-C instance variables (including automatically
491 // synthesized instance variables), if we're in an Objective-C method.
492 // FIXME: This lookup really, really needs to be folded in to the normal
493 // unqualified lookup mechanism.
494 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
495 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorec385cf2011-04-25 15:05:41 +0000496 if (E.get() || E.isInvalid())
Douglas Gregor312eadb2011-04-24 05:37:28 +0000497 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000498 }
499
500 bool SecondTry = false;
501 bool IsFilteredTemplateName = false;
502
503Corrected:
504 switch (Result.getResultKind()) {
505 case LookupResult::NotFound:
506 // If an unqualified-id is followed by a '(', then we have a function
507 // call.
508 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
509 // In C++, this is an ADL-only call.
510 // FIXME: Reference?
David Blaikie4e4d0842012-03-11 07:00:24 +0000511 if (getLangOpts().CPlusPlus)
Douglas Gregor312eadb2011-04-24 05:37:28 +0000512 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
513
514 // C90 6.3.2.2:
515 // If the expression that precedes the parenthesized argument list in a
516 // function call consists solely of an identifier, and if no
517 // declaration is visible for this identifier, the identifier is
518 // implicitly declared exactly as if, in the innermost block containing
519 // the function call, the declaration
520 //
521 // extern int identifier ();
522 //
523 // appeared.
524 //
525 // We also allow this in C99 as an extension.
526 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
527 Result.addDecl(D);
528 Result.resolveKind();
529 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
530 }
531 }
532
533 // In C, we first see whether there is a tag type by the same name, in
534 // which case it's likely that the user just forget to write "enum",
535 // "struct", or "union".
David Blaikie4e4d0842012-03-11 07:00:24 +0000536 if (!getLangOpts().CPlusPlus && !SecondTry) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000537 Result.clear(LookupTagName);
538 LookupParsedName(Result, S, &SS);
539 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
540 const char *TagName = 0;
541 const char *FixItTagName = 0;
542 switch (Tag->getTagKind()) {
543 case TTK_Class:
544 TagName = "class";
545 FixItTagName = "class ";
546 break;
547
548 case TTK_Enum:
549 TagName = "enum";
550 FixItTagName = "enum ";
551 break;
552
553 case TTK_Struct:
554 TagName = "struct";
555 FixItTagName = "struct ";
556 break;
557
558 case TTK_Union:
559 TagName = "union";
560 FixItTagName = "union ";
561 break;
562 }
563
564 Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
David Blaikie4e4d0842012-03-11 07:00:24 +0000565 << Name << TagName << getLangOpts().CPlusPlus
Douglas Gregor312eadb2011-04-24 05:37:28 +0000566 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
Kaelyn Uhrainaec2ac62012-04-26 23:36:17 +0000567
568 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
569 if (LookupParsedName(R, S, &SS)) {
570 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
571 I != IEnd; ++I)
Kaelyn Uhrain392b3f52012-04-27 18:26:49 +0000572 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrainaec2ac62012-04-26 23:36:17 +0000573 << Name << TagName;
574 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000575 break;
576 }
577
578 Result.clear(LookupOrdinaryName);
579 }
580
581 // Perform typo correction to determine if there is another name that is
582 // close to this name.
583 if (!SecondTry) {
Douglas Gregor3a348c82011-07-14 04:54:23 +0000584 SecondTry = true;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000585 CorrectionCandidateCallback DefaultValidator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000586 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikied662a792011-10-19 22:56:21 +0000587 Result.getLookupKind(), S,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000588 &SS, DefaultValidator)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000589 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
590 unsigned QualifiedDiag = diag::err_no_member_suggest;
David Blaikie4e4d0842012-03-11 07:00:24 +0000591 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
592 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor27766d22011-04-27 03:47:06 +0000593
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000594 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor3b887352011-04-27 04:48:22 +0000595 NamedDecl *UnderlyingFirstDecl
596 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikie4e4d0842012-03-11 07:00:24 +0000597 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000598 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000599 UnqualifiedDiag = diag::err_no_template_suggest;
600 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor3b887352011-04-27 04:48:22 +0000601 } else if (UnderlyingFirstDecl &&
602 (isa<TypeDecl>(UnderlyingFirstDecl) ||
603 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
604 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000605 UnqualifiedDiag = diag::err_unknown_typename_suggest;
606 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
607 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000608
Douglas Gregor312eadb2011-04-24 05:37:28 +0000609 if (SS.isEmpty())
Douglas Gregor27766d22011-04-27 03:47:06 +0000610 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000611 << Name << CorrectedQuotedStr
612 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000613 else
Douglas Gregor27766d22011-04-27 03:47:06 +0000614 Diag(NameLoc, QualifiedDiag)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000615 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor312eadb2011-04-24 05:37:28 +0000616 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000617 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000618
619 // Update the name, so that the caller has the new name.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000620 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000621
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000622 // Typo correction corrected to a keyword.
623 if (Corrected.isKeyword())
624 return Corrected.getCorrectionAsIdentifierInfo();
625
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000626 // Also update the LookupResult...
627 // FIXME: This should probably go away at some point
628 Result.clear();
629 Result.setLookupName(Corrected.getCorrection());
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000630 if (FirstDecl) {
631 Result.addDecl(FirstDecl);
Douglas Gregor3a348c82011-07-14 04:54:23 +0000632 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
633 << CorrectedQuotedStr;
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000634 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000635
636 // If we found an Objective-C instance variable, let
637 // LookupInObjCMethod build the appropriate expression to
638 // reference the ivar.
639 // FIXME: This is a gross hack.
640 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
641 Result.clear();
642 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
643 return move(E);
644 }
645
646 goto Corrected;
647 }
648 }
649
650 // We failed to correct; just fall through and let the parser deal with it.
651 Result.suppressDiagnostics();
652 return NameClassification::Unknown();
653
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000654 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000655 // We performed name lookup into the current instantiation, and there were
656 // dependent bases, so we treat this result the same way as any other
657 // dependent nested-name-specifier.
658
659 // C++ [temp.res]p2:
660 // A name used in a template declaration or definition and that is
661 // dependent on a template-parameter is assumed not to name a type
662 // unless the applicable name lookup finds a type name or the name is
663 // qualified by the keyword typename.
664 //
665 // FIXME: If the next token is '<', we might want to ask the parser to
666 // perform some heroics to see if we actually have a
667 // template-argument-list, which would indicate a missing 'template'
668 // keyword here.
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000669 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
670 NameInfo, /*TemplateArgs=*/0);
671 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000672
673 case LookupResult::Found:
674 case LookupResult::FoundOverloaded:
675 case LookupResult::FoundUnresolvedValue:
676 break;
677
678 case LookupResult::Ambiguous:
David Blaikie4e4d0842012-03-11 07:00:24 +0000679 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000680 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000681 // C++ [temp.local]p3:
682 // A lookup that finds an injected-class-name (10.2) can result in an
683 // ambiguity in certain cases (for example, if it is found in more than
684 // one base class). If all of the injected-class-names that are found
685 // refer to specializations of the same class template, and if the name
686 // is followed by a template-argument-list, the reference refers to the
687 // class template itself and not a specialization thereof, and is not
688 // ambiguous.
689 //
690 // This filtering can make an ambiguous result into an unambiguous one,
691 // so try again after filtering out template names.
692 FilterAcceptableTemplateNames(Result);
693 if (!Result.isAmbiguous()) {
694 IsFilteredTemplateName = true;
695 break;
696 }
697 }
698
699 // Diagnose the ambiguity and return an error.
700 return NameClassification::Error();
701 }
702
David Blaikie4e4d0842012-03-11 07:00:24 +0000703 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000704 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
705 // C++ [temp.names]p3:
706 // After name lookup (3.4) finds that a name is a template-name or that
707 // an operator-function-id or a literal- operator-id refers to a set of
708 // overloaded functions any member of which is a function template if
709 // this is followed by a <, the < is always taken as the delimiter of a
710 // template-argument-list and never as the less-than operator.
711 if (!IsFilteredTemplateName)
712 FilterAcceptableTemplateNames(Result);
713
Douglas Gregor3b887352011-04-27 04:48:22 +0000714 if (!Result.empty()) {
715 bool IsFunctionTemplate;
716 TemplateName Template;
717 if (Result.end() - Result.begin() > 1) {
718 IsFunctionTemplate = true;
719 Template = Context.getOverloadedTemplateName(Result.begin(),
720 Result.end());
721 } else {
722 TemplateDecl *TD
723 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
724 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
725
726 if (SS.isSet() && !SS.isInvalid())
727 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000728 /*TemplateKeyword=*/false,
Douglas Gregor3b887352011-04-27 04:48:22 +0000729 TD);
730 else
731 Template = TemplateName(TD);
732 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000733
Douglas Gregor3b887352011-04-27 04:48:22 +0000734 if (IsFunctionTemplate) {
735 // Function templates always go through overload resolution, at which
736 // point we'll perform the various checks (e.g., accessibility) we need
737 // to based on which function we selected.
738 Result.suppressDiagnostics();
739
740 return NameClassification::FunctionTemplate(Template);
741 }
742
743 return NameClassification::TypeTemplate(Template);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000744 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000745 }
746
Douglas Gregor3b887352011-04-27 04:48:22 +0000747 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000748 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
749 DiagnoseUseOfDecl(Type, NameLoc);
750 QualType T = Context.getTypeDeclType(Type);
751 return ParsedType::make(T);
752 }
753
754 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
755 if (!Class) {
756 // FIXME: It's unfortunate that we don't have a Type node for handling this.
757 if (ObjCCompatibleAliasDecl *Alias
758 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
759 Class = Alias->getClassInterface();
760 }
761
762 if (Class) {
763 DiagnoseUseOfDecl(Class, NameLoc);
764
765 if (NextToken.is(tok::period)) {
766 // Interface. <something> is parsed as a property reference expression.
767 // Just return "unknown" as a fall-through for now.
768 Result.suppressDiagnostics();
769 return NameClassification::Unknown();
770 }
771
772 QualType T = Context.getObjCInterfaceType(Class);
773 return ParsedType::make(T);
774 }
775
Douglas Gregor3b887352011-04-27 04:48:22 +0000776 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000777 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor3b887352011-04-27 04:48:22 +0000778
Douglas Gregor312eadb2011-04-24 05:37:28 +0000779 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
780 return BuildDeclarationNameExpr(SS, Result, ADL);
781}
782
John McCall88232aa2009-08-18 00:00:49 +0000783// Determines the context to return to after temporarily entering a
784// context. This depends in an unnecessarily complicated way on the
785// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000786DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000787
John McCall88232aa2009-08-18 00:00:49 +0000788 // Functions defined inline within classes aren't parsed until we've
789 // finished parsing the top-level class, so the top-level class is
790 // the context we'll need to return to.
791 if (isa<FunctionDecl>(DC)) {
792 DC = DC->getLexicalParent();
793
794 // A function not defined within a class will always return to its
795 // lexical context.
796 if (!isa<CXXRecordDecl>(DC))
797 return DC;
798
799 // A C++ inline method/friend is parsed *after* the topmost class
800 // it was declared in is fully parsed ("complete"); the topmost
801 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000802 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000803 DC = RD;
804
805 // Return the declaration context of the topmost class the inline method is
806 // declared in.
807 return DC;
808 }
809
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000810 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811}
812
Douglas Gregor44b43212008-12-11 16:49:14 +0000813void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000814 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000815 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000816 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000817 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000818}
819
Chris Lattnerb048c982008-04-06 04:47:34 +0000820void Sema::PopDeclContext() {
821 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000822
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000823 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000824 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000825}
826
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000827/// EnterDeclaratorContext - Used when we must lookup names in the context
828/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000829///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000830void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000831 // C++0x [basic.lookup.unqual]p13:
832 // A name used in the definition of a static data member of class
833 // X (after the qualified-id of the static member) is looked up as
834 // if the name was used in a member function of X.
835 // C++0x [basic.lookup.unqual]p14:
836 // If a variable member of a namespace is defined outside of the
837 // scope of its namespace then any name used in the definition of
838 // the variable member (after the declarator-id) is looked up as
839 // if the definition of the variable member occurred in its
840 // namespace.
841 // Both of these imply that we should push a scope whose context
842 // is the semantic context of the declaration. We can't use
843 // PushDeclContext here because that context is not necessarily
844 // lexically contained in the current context. Fortunately,
845 // the containing scope should have the appropriate information.
846
847 assert(!S->getEntity() && "scope already has entity");
848
849#ifndef NDEBUG
850 Scope *Ancestor = S->getParent();
851 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
852 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
853#endif
854
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000855 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000856 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000857}
858
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000859void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000860 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000861
John McCall7a1dc562009-12-19 10:49:29 +0000862 // Switch back to the lexical context. The safety of this is
863 // enforced by an assert in EnterDeclaratorContext.
864 Scope *Ancestor = S->getParent();
865 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
866 CurContext = (DeclContext*) Ancestor->getEntity();
867
868 // We don't need to do anything with the scope, which is going to
869 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000870}
871
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000872
873void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
874 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
875 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
876 // We assume that the caller has already called
877 // ActOnReenterTemplateScope
878 FD = TFD->getTemplatedDecl();
879 }
880 if (!FD)
881 return;
882
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000883 // Same implementation as PushDeclContext, but enters the context
884 // from the lexical parent, rather than the top-level class.
885 assert(CurContext == FD->getLexicalParent() &&
886 "The next DeclContext should be lexically contained in the current one.");
887 CurContext = FD;
888 S->setEntity(CurContext);
889
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000890 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
891 ParmVarDecl *Param = FD->getParamDecl(P);
892 // If the parameter has an identifier, then add it to the scope
893 if (Param->getIdentifier()) {
894 S->AddDecl(Param);
895 IdResolver.AddDecl(Param);
896 }
897 }
898}
899
900
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000901void Sema::ActOnExitFunctionContext() {
902 // Same implementation as PopDeclContext, but returns to the lexical parent,
903 // rather than the top-level class.
904 assert(CurContext && "DeclContext imbalance!");
905 CurContext = CurContext->getLexicalParent();
906 assert(CurContext && "Popped translation unit!");
907}
908
909
Douglas Gregorf9201e02009-02-11 23:02:49 +0000910/// \brief Determine whether we allow overloading of the function
911/// PrevDecl with another declaration.
912///
913/// This routine determines whether overloading is possible, not
914/// whether some new function is actually an overload. It will return
915/// true in C++ (where we can always provide overloads) or, as an
916/// extension, in C when the previous function is already an
917/// overloaded function declaration or has the "overloadable"
918/// attribute.
John McCall68263142009-11-18 22:49:29 +0000919static bool AllowOverloadingOfFunction(LookupResult &Previous,
920 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000921 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000922 return true;
923
John McCall68263142009-11-18 22:49:29 +0000924 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000925 return true;
926
John McCall68263142009-11-18 22:49:29 +0000927 return (Previous.getResultKind() == LookupResult::Found
928 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +0000929}
930
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000931/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +0000932void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000933 // Move up the scope chain until we find the nearest enclosing
934 // non-transparent context. The declaration will be introduced into this
935 // scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000936 while (S->getEntity() &&
Douglas Gregor074149e2009-01-05 19:45:36 +0000937 ((DeclContext *)S->getEntity())->isTransparentContext())
938 S = S->getParent();
939
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000940 // Add scoped declarations into their context, so that they can be
941 // found later. Declarations without a context won't be inserted
942 // into any context.
John McCallab88d972009-08-31 22:39:49 +0000943 if (AddToContext)
944 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000945
Chandler Carruth8761d682010-02-21 07:08:09 +0000946 // Out-of-line definitions shouldn't be pushed into scope in C++.
947 // Out-of-line variable and function definitions shouldn't even in C.
David Blaikie4e4d0842012-03-11 07:00:24 +0000948 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +0000949 D->isOutOfLine() &&
950 !D->getDeclContext()->getRedeclContext()->Equals(
951 D->getLexicalDeclContext()->getRedeclContext()))
Chandler Carruth8761d682010-02-21 07:08:09 +0000952 return;
953
954 // Template instantiations should also not be pushed into scope.
955 if (isa<FunctionDecl>(D) &&
956 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +0000957 return;
958
John McCallf36e02d2009-10-09 21:13:30 +0000959 // If this replaces anything in the current scope,
960 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
961 IEnd = IdResolver.end();
962 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +0000963 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
964 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +0000965 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000966
John McCallf36e02d2009-10-09 21:13:30 +0000967 // Should only need to replace one decl.
968 break;
Douglas Gregor516ff432009-04-24 02:57:34 +0000969 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000970 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000971
John McCalld226f652010-08-21 09:40:31 +0000972 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +0000973
974 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
975 // Implicitly-generated labels may end up getting generated in an order that
976 // isn't strictly lexical, which breaks name lookup. Be careful to insert
977 // the label at the appropriate place in the identifier chain.
978 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +0000979 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +0000980 if (IDC == CurContext) {
981 if (!S->isDeclScope(*I))
982 continue;
983 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +0000984 break;
985 }
986
Douglas Gregor250e7a72011-03-16 16:39:03 +0000987 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +0000988 } else {
989 IdResolver.AddDecl(D);
990 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000991}
992
Douglas Gregoreee242f2011-10-27 09:33:13 +0000993void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
994 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
995 TUScope->AddDecl(D);
996}
997
Douglas Gregorcc209452011-03-07 16:54:27 +0000998bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
999 bool ExplicitInstantiationOrSpecialization) {
1000 return IdResolver.isDeclInScope(D, Ctx, Context, S,
1001 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001002}
1003
John McCall5f1e0942010-08-24 08:50:51 +00001004Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1005 DeclContext *TargetDC = DC->getPrimaryContext();
1006 do {
1007 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1008 if (ScopeDC->getPrimaryContext() == TargetDC)
1009 return S;
1010 } while ((S = S->getParent()));
1011
1012 return 0;
1013}
1014
John McCall68263142009-11-18 22:49:29 +00001015static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1016 DeclContext*,
1017 ASTContext&);
1018
1019/// Filters out lookup results that don't fall within the given scope
1020/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001021void Sema::FilterLookupForScope(LookupResult &R,
1022 DeclContext *Ctx, Scope *S,
1023 bool ConsiderLinkage,
1024 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001025 LookupResult::Filter F = R.makeFilter();
1026 while (F.hasNext()) {
1027 NamedDecl *D = F.next();
1028
Richard Smith3e4c6c42011-05-05 21:57:07 +00001029 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001030 continue;
1031
1032 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001033 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001034 continue;
1035
1036 F.erase();
1037 }
1038
1039 F.done();
1040}
1041
1042static bool isUsingDecl(NamedDecl *D) {
1043 return isa<UsingShadowDecl>(D) ||
1044 isa<UnresolvedUsingTypenameDecl>(D) ||
1045 isa<UnresolvedUsingValueDecl>(D);
1046}
1047
1048/// Removes using shadow declarations from the lookup results.
1049static void RemoveUsingDecls(LookupResult &R) {
1050 LookupResult::Filter F = R.makeFilter();
1051 while (F.hasNext())
1052 if (isUsingDecl(F.next()))
1053 F.erase();
1054
1055 F.done();
1056}
1057
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001058/// \brief Check for this common pattern:
1059/// @code
1060/// class S {
1061/// S(const S&); // DO NOT IMPLEMENT
1062/// void operator=(const S&); // DO NOT IMPLEMENT
1063/// };
1064/// @endcode
1065static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1066 // FIXME: Should check for private access too but access is set after we get
1067 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001068 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001069 return false;
1070
1071 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1072 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001073 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1074 return Method->isCopyAssignmentOperator();
1075 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001076}
1077
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001078bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1079 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001080
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001081 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1082 return false;
1083
1084 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001085 if (D->getDeclContext()->isDependentContext() ||
1086 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001087 return false;
1088
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001089 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001090 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1091 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001092
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001093 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1094 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1095 return false;
1096 } else {
1097 // 'static inline' functions are used in headers; don't warn.
John McCalld931b082010-08-26 03:08:43 +00001098 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001099 FD->isInlineSpecified())
1100 return false;
1101 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001102
Sean Hunt10620eb2011-05-06 20:44:56 +00001103 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001104 Context.DeclMustBeEmitted(FD))
1105 return false;
John McCall82b96592010-10-27 01:41:35 +00001106 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1107 if (!VD->isFileVarDecl() ||
1108 VD->getType().isConstant(Context) ||
1109 Context.DeclMustBeEmitted(VD))
1110 return false;
1111
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001112 if (VD->isStaticDataMember() &&
1113 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1114 return false;
1115
John McCall82b96592010-10-27 01:41:35 +00001116 } else {
1117 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001118 }
1119
John McCall82b96592010-10-27 01:41:35 +00001120 // Only warn for unused decls internal to the translation unit.
1121 if (D->getLinkage() == ExternalLinkage)
1122 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001123
John McCall82b96592010-10-27 01:41:35 +00001124 return true;
1125}
1126
1127void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001128 if (!D)
1129 return;
1130
1131 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1132 const FunctionDecl *First = FD->getFirstDeclaration();
1133 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1134 return; // First should already be in the vector.
1135 }
1136
1137 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1138 const VarDecl *First = VD->getFirstDeclaration();
1139 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1140 return; // First should already be in the vector.
1141 }
1142
1143 if (ShouldWarnIfUnusedFileScopedDecl(D))
1144 UnusedFileScopedDecls.push_back(D);
1145 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001146
Anders Carlsson99a000e2009-11-07 07:18:14 +00001147static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001148 if (D->isInvalidDecl())
1149 return false;
1150
Eli Friedmandd9d6452012-01-13 23:41:25 +00001151 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001152 return false;
John McCall86ff3082010-02-04 22:26:26 +00001153
Chris Lattner57ad3782011-02-17 20:34:02 +00001154 if (isa<LabelDecl>(D))
1155 return true;
1156
John McCall86ff3082010-02-04 22:26:26 +00001157 // White-list anything that isn't a local variable.
1158 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1159 !D->getDeclContext()->isFunctionOrMethod())
1160 return false;
1161
1162 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001163 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001164
1165 // White-list anything with an __attribute__((unused)) type.
1166 QualType Ty = VD->getType();
1167
1168 // Only look at the outermost level of typedef.
1169 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1170 if (TT->getDecl()->hasAttr<UnusedAttr>())
1171 return false;
1172 }
1173
Douglas Gregor5764f612010-05-08 23:05:03 +00001174 // If we failed to complete the type for some reason, or if the type is
1175 // dependent, don't diagnose the variable.
1176 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001177 return false;
1178
John McCallaec58602010-03-31 02:47:45 +00001179 if (const TagType *TT = Ty->getAs<TagType>()) {
1180 const TagDecl *Tag = TT->getDecl();
1181 if (Tag->hasAttr<UnusedAttr>())
1182 return false;
1183
1184 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001185 if (!RD->hasTrivialDestructor())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001186 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001187
1188 if (const Expr *Init = VD->getInit()) {
1189 const CXXConstructExpr *Construct =
1190 dyn_cast<CXXConstructExpr>(Init);
1191 if (Construct && !Construct->isElidable()) {
1192 CXXConstructorDecl *CD = Construct->getConstructor();
1193 if (!CD->isTrivial())
1194 return false;
1195 }
1196 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001197 }
1198 }
John McCallaec58602010-03-31 02:47:45 +00001199
1200 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001201 }
1202
John McCall86ff3082010-02-04 22:26:26 +00001203 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001204}
1205
Anna Zaksd5612a22011-07-28 20:52:06 +00001206static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1207 FixItHint &Hint) {
1208 if (isa<LabelDecl>(D)) {
1209 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001211 if (AfterColon.isInvalid())
1212 return;
1213 Hint = FixItHint::CreateRemoval(CharSourceRange::
1214 getCharRange(D->getLocStart(), AfterColon));
1215 }
1216 return;
1217}
1218
Chris Lattner337e5502011-02-18 01:27:55 +00001219/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1220/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001221void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001222 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001223 if (!ShouldDiagnoseUnusedDecl(D))
1224 return;
1225
Anna Zaksd5612a22011-07-28 20:52:06 +00001226 GenerateFixForUnusedDecl(D, Context, Hint);
1227
Chris Lattner57ad3782011-02-17 20:34:02 +00001228 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001229 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001230 DiagID = diag::warn_unused_exception_param;
1231 else if (isa<LabelDecl>(D))
1232 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001233 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001234 DiagID = diag::warn_unused_variable;
1235
Anna Zaksd5612a22011-07-28 20:52:06 +00001236 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001237}
1238
Chris Lattner337e5502011-02-18 01:27:55 +00001239static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1240 // Verify that we have no forward references left. If so, there was a goto
1241 // or address of a label taken, but no definition of it. Label fwd
1242 // definitions are indicated with a null substmt.
1243 if (L->getStmt() == 0)
1244 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1245}
1246
Steve Naroffb216c882007-10-09 22:01:59 +00001247void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001248 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001249 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001250 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001251
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1253 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001254 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001255 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001256
Douglas Gregor44b43212008-12-11 16:49:14 +00001257 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1258 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001259
Douglas Gregor44b43212008-12-11 16:49:14 +00001260 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001261
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001262 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00001263 if (!S->hasErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001264 DiagnoseUnusedDecl(D);
1265
Chris Lattner337e5502011-02-18 01:27:55 +00001266 // If this was a forward reference to a label, verify it was defined.
1267 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1268 CheckPoppedLabel(LD, *this);
1269
Douglas Gregor44b43212008-12-11 16:49:14 +00001270 // Remove this name from our lexical scope.
1271 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 }
1273}
1274
James Molloy16f1f712012-02-29 10:24:19 +00001275void Sema::ActOnStartFunctionDeclarator() {
1276 ++InFunctionDeclarator;
1277}
1278
1279void Sema::ActOnEndFunctionDeclarator() {
1280 assert(InFunctionDeclarator);
1281 --InFunctionDeclarator;
1282}
1283
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001284/// \brief Look for an Objective-C class in the translation unit.
1285///
1286/// \param Id The name of the Objective-C class we're looking for. If
1287/// typo-correction fixes this name, the Id will be updated
1288/// to the fixed name.
1289///
1290/// \param IdLoc The location of the name in the translation unit.
1291///
1292/// \param TypoCorrection If true, this routine will attempt typo correction
1293/// if there is no class with the given name.
1294///
1295/// \returns The declaration of the named Objective-C class, or NULL if the
1296/// class could not be found.
1297ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1298 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001299 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001300 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1301 // creation from this context.
1302 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1303
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001304 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001305 // Perform typo correction at the given location, but only if we
1306 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001307 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1308 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1309 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001310 Validator)) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001311 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001312 Diag(IdLoc, diag::err_undef_interface_suggest)
1313 << Id << IDecl->getDeclName()
1314 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1315 Diag(IDecl->getLocation(), diag::note_previous_decl)
1316 << IDecl->getDeclName();
1317
1318 Id = IDecl->getIdentifier();
1319 }
1320 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001321 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1322 // This routine must always return a class definition, if any.
1323 if (Def && Def->getDefinition())
1324 Def = Def->getDefinition();
1325 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001326}
1327
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001328/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1329/// from S, where a non-field would be declared. This routine copes
1330/// with the difference between C and C++ scoping rules in structs and
1331/// unions. For example, the following code is well-formed in C but
1332/// ill-formed in C++:
1333/// @code
1334/// struct S6 {
1335/// enum { BAR } e;
1336/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001337///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001338/// void test_S6() {
1339/// struct S6 a;
1340/// a.e = BAR;
1341/// }
1342/// @endcode
1343/// For the declaration of BAR, this routine will return a different
1344/// scope. The scope S will be the scope of the unnamed enumeration
1345/// within S6. In C++, this routine will return the scope associated
1346/// with S6, because the enumeration's scope is a transparent
1347/// context but structures can contain non-field names. In C, this
1348/// routine will return the translation unit scope, since the
1349/// enumeration's scope is a transparent context and structures cannot
1350/// contain non-field names.
1351Scope *Sema::getNonFieldDeclScope(Scope *S) {
1352 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001353 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001354 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001355 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001356 S = S->getParent();
1357 return S;
1358}
1359
Douglas Gregor3e41d602009-02-13 23:20:09 +00001360/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1361/// file scope. lazily create a decl for it. ForRedeclaration is true
1362/// if we're creating this built-in in anticipation of redeclaring the
1363/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001364NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001365 Scope *S, bool ForRedeclaration,
1366 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 Builtin::ID BID = (Builtin::ID)bid;
1368
Chris Lattner86df27b2009-06-14 00:45:47 +00001369 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001370 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001371 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001372 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001373 // Okay
1374 break;
1375
Mike Stumpf711c412009-07-28 23:57:15 +00001376 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001377 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001378 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001379 << Context.BuiltinInfo.GetName(BID);
1380 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001381
Mike Stumpf711c412009-07-28 23:57:15 +00001382 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001383 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001384 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001385 << Context.BuiltinInfo.GetName(BID);
1386 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001387
1388 case ASTContext::GE_Missing_ucontext:
1389 if (ForRedeclaration)
1390 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1391 << Context.BuiltinInfo.GetName(BID);
1392 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001393 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001394
1395 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1396 Diag(Loc, diag::ext_implicit_lib_function_decl)
1397 << Context.BuiltinInfo.GetName(BID)
1398 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001399 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001400 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001401 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001402 Diag(Loc, diag::note_please_include_header)
1403 << Context.BuiltinInfo.getHeaderName(BID)
1404 << Context.BuiltinInfo.GetName(BID);
1405 }
1406
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001407 FunctionDecl *New = FunctionDecl::Create(Context,
1408 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001409 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001410 SC_Extern,
1411 SC_None, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001412 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001413 New->setImplicit();
1414
Chris Lattner95e2c712008-05-05 22:18:14 +00001415 // Create Decl objects for each parameter, adding them to the
1416 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001417 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001418 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001419 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1420 ParmVarDecl *parm =
1421 ParmVarDecl::Create(Context, New, SourceLocation(),
1422 SourceLocation(), 0,
1423 FT->getArgType(i), /*TInfo=*/0,
1424 SC_None, SC_None, 0);
1425 parm->setScopeInfo(0, i);
1426 Params.push_back(parm);
1427 }
David Blaikie4278c652011-09-21 18:16:56 +00001428 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
1431 AddKnownFunctionAttributes(New);
1432
Chris Lattner7f925cc2008-04-11 07:00:53 +00001433 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001434 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1435 // relate Scopes to DeclContexts, and probably eliminate CurContext
1436 // entirely, but we're not there yet.
1437 DeclContext *SavedContext = CurContext;
1438 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001439 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001440 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 return New;
1442}
1443
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001444bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1445 QualType OldType;
1446 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1447 OldType = OldTypedef->getUnderlyingType();
1448 else
1449 OldType = Context.getTypeDeclType(Old);
1450 QualType NewType = New->getUnderlyingType();
1451
Douglas Gregorec3bd722012-01-11 22:33:48 +00001452 if (NewType->isVariablyModifiedType()) {
1453 // Must not redefine a typedef with a variably-modified type.
1454 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1455 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1456 << Kind << NewType;
1457 if (Old->getLocation().isValid())
1458 Diag(Old->getLocation(), diag::note_previous_definition);
1459 New->setInvalidDecl();
1460 return true;
1461 }
1462
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001463 if (OldType != NewType &&
1464 !OldType->isDependentType() &&
1465 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001466 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001467 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1468 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1469 << Kind << NewType << OldType;
1470 if (Old->getLocation().isValid())
1471 Diag(Old->getLocation(), diag::note_previous_definition);
1472 New->setInvalidDecl();
1473 return true;
1474 }
1475 return false;
1476}
1477
Richard Smith162e1c12011-04-15 14:24:37 +00001478/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001479/// same name and scope as a previous declaration 'Old'. Figure out
1480/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001481/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001482///
Richard Smith162e1c12011-04-15 14:24:37 +00001483void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001484 // If the new decl is known invalid already, don't bother doing any
1485 // merging checks.
1486 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Steve Naroff2b255c42008-09-09 14:32:20 +00001488 // Allow multiple definitions for ObjC built-in typedefs.
1489 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001490 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001491 const IdentifierInfo *TypeID = New->getIdentifier();
1492 switch (TypeID->getLength()) {
1493 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001494 case 2:
Chris Lattner2bac0f62008-11-20 05:41:43 +00001495 if (!TypeID->isStr("id"))
1496 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001497 Context.setObjCIdRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001498 // Install the built-in type for 'id', ignoring the current definition.
1499 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1500 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001501 case 5:
1502 if (!TypeID->isStr("Class"))
1503 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001504 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001505 // Install the built-in type for 'Class', ignoring the current definition.
1506 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001507 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001508 case 3:
1509 if (!TypeID->isStr("SEL"))
1510 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001511 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001512 // Install the built-in type for 'SEL', ignoring the current definition.
1513 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001514 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001515 }
1516 // Fall through - the typedef name was not a builtin type.
1517 }
John McCall68263142009-11-18 22:49:29 +00001518
Douglas Gregor66973122009-01-28 17:15:10 +00001519 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001520 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1521 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001522 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001523 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001524
1525 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001526 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001527 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001528
Chris Lattnereaaebc72009-04-25 08:06:05 +00001529 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 }
Douglas Gregor66973122009-01-28 17:15:10 +00001531
John McCall68263142009-11-18 22:49:29 +00001532 // If the old declaration is invalid, just give up here.
1533 if (Old->isInvalidDecl())
1534 return New->setInvalidDecl();
1535
Chris Lattner99cb9972008-07-25 18:44:27 +00001536 // If the typedef types are not identical, reject them in all languages and
1537 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001538 if (isIncompatibleTypedef(Old, New))
1539 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001540
John McCall5126fd02009-12-30 00:31:22 +00001541 // The types match. Link up the redeclaration chain if the old
1542 // declaration was a typedef.
Richard Smith162e1c12011-04-15 14:24:37 +00001543 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1544 New->setPreviousDeclaration(Typedef);
John McCall5126fd02009-12-30 00:31:22 +00001545
David Blaikie4e4d0842012-03-11 07:00:24 +00001546 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001547 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001548
David Blaikie4e4d0842012-03-11 07:00:24 +00001549 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001550 // C++ [dcl.typedef]p2:
1551 // In a given non-class scope, a typedef specifier can be used to
1552 // redefine the name of any type declared in that scope to refer
1553 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001554 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001555 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001556
1557 // C++0x [dcl.typedef]p4:
1558 // In a given class scope, a typedef specifier can be used to redefine
1559 // any class-name declared in that scope that is not also a typedef-name
1560 // to refer to the type to which it already refers.
1561 //
1562 // This wording came in via DR424, which was a correction to the
1563 // wording in DR56, which accidentally banned code like:
1564 //
1565 // struct S {
1566 // typedef struct A { } A;
1567 // };
1568 //
1569 // in the C++03 standard. We implement the C++0x semantics, which
1570 // allow the above but disallow
1571 //
1572 // struct S {
1573 // typedef int I;
1574 // typedef int I;
1575 // };
1576 //
1577 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001578 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001579 return;
1580
Chris Lattner32b06752009-04-17 22:04:20 +00001581 Diag(New->getLocation(), diag::err_redefinition)
1582 << New->getDeclName();
1583 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001584 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001585 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001586
Douglas Gregorc0004df2012-01-11 04:25:01 +00001587 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001588 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001589 return;
1590
Chris Lattner32b06752009-04-17 22:04:20 +00001591 // If we have a redefinition of a typedef in C, emit a warning. This warning
1592 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001593 // -Wtypedef-redefinition. If either the original or the redefinition is
1594 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001595 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001596 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1597 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001598 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattner32b06752009-04-17 22:04:20 +00001600 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1601 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001602 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001603 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604}
1605
Chris Lattner6b6b5372008-06-26 18:38:35 +00001606/// DeclhasAttr - returns true if decl Declaration already has the target
1607/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001608static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001609DeclHasAttr(const Decl *D, const Attr *A) {
1610 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001611 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001612 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1613 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001614 if (Ann) {
1615 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1616 return true;
1617 continue;
1618 }
Sean Huntcf807c42010-08-18 23:23:40 +00001619 // FIXME: Don't hardcode this check
1620 if (OA && isa<OwnershipAttr>(*i))
1621 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001622 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001623 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001624
1625 return false;
1626}
1627
John McCalleca5d222011-03-02 04:00:57 +00001628/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Douglas Gregor27c6da22012-01-01 20:30:41 +00001629void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1630 bool MergeDeprecation) {
1631 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00001632 return;
John McCalleca5d222011-03-02 04:00:57 +00001633
Douglas Gregor27c6da22012-01-01 20:30:41 +00001634 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00001635
Sean Huntcf807c42010-08-18 23:23:40 +00001636 // Ensure that any moving of objects within the allocated map is done before
1637 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00001638 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00001639
Peter Collingbournea97d70b2011-01-21 02:08:36 +00001640 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00001641 i = Old->specific_attr_begin<InheritableAttr>(),
1642 e = Old->specific_attr_end<InheritableAttr>();
1643 i != e; ++i) {
Douglas Gregorc193dd82011-09-23 20:23:42 +00001644 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor27c6da22012-01-01 20:30:41 +00001645 if (!MergeDeprecation &&
Douglas Gregorc193dd82011-09-23 20:23:42 +00001646 (isa<DeprecatedAttr>(*i) ||
1647 isa<UnavailableAttr>(*i) ||
1648 isa<AvailabilityAttr>(*i)))
John McCall6c2c2502011-07-22 02:45:48 +00001649 continue;
1650
Douglas Gregor27c6da22012-01-01 20:30:41 +00001651 if (!DeclHasAttr(New, *i)) {
1652 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
John McCalleca5d222011-03-02 04:00:57 +00001653 newAttr->setInherited(true);
Douglas Gregor27c6da22012-01-01 20:30:41 +00001654 New->addAttr(newAttr);
John McCalleca5d222011-03-02 04:00:57 +00001655 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00001656 }
1657 }
John McCalleca5d222011-03-02 04:00:57 +00001658
Douglas Gregor27c6da22012-01-01 20:30:41 +00001659 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00001660}
1661
1662/// mergeParamDeclAttributes - Copy attributes from the old parameter
1663/// to the new one.
1664static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1665 const ParmVarDecl *oldDecl,
1666 ASTContext &C) {
1667 if (!oldDecl->hasAttrs())
1668 return;
1669
1670 bool foundAny = newDecl->hasAttrs();
1671
1672 // Ensure that any moving of objects within the allocated map is
1673 // done before we process them.
1674 if (!foundAny) newDecl->setAttrs(AttrVec());
1675
1676 for (specific_attr_iterator<InheritableParamAttr>
1677 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1678 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1679 if (!DeclHasAttr(newDecl, *i)) {
1680 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1681 newAttr->setInherited(true);
1682 newDecl->addAttr(newAttr);
1683 foundAny = true;
1684 }
1685 }
1686
1687 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00001688}
1689
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001690namespace {
1691
Douglas Gregorc8376562009-03-06 22:43:54 +00001692/// Used in MergeFunctionDecl to keep track of function parameters in
1693/// C.
1694struct GNUCompatibleParamWarning {
1695 ParmVarDecl *OldParm;
1696 ParmVarDecl *NewParm;
1697 QualType PromotedType;
1698};
1699
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001700}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001701
1702/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001703Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001704 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00001705 if (Ctor->isDefaultConstructor())
1706 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00001707
1708 if (Ctor->isCopyConstructor())
1709 return Sema::CXXCopyConstructor;
1710
1711 if (Ctor->isMoveConstructor())
1712 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00001713 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001714 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00001715 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00001716 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00001717 } else if (MD->isMoveAssignmentOperator()) {
1718 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00001719 }
Sean Huntf961ea52011-05-10 19:08:14 +00001720
Sean Huntf961ea52011-05-10 19:08:14 +00001721 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001722}
1723
Sebastian Redl515ddd82010-06-09 21:17:41 +00001724/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001725/// only extern inline functions can be redefined, and even then only in
1726/// GNU89 mode.
1727static bool canRedefineFunction(const FunctionDecl *FD,
1728 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00001729 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1730 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001731 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00001732 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001733}
1734
Chris Lattner04421082008-04-08 04:40:51 +00001735/// MergeFunctionDecl - We just parsed a function 'New' from
1736/// declarator D which has the same name and scope as a previous
1737/// declaration 'Old'. Figure out how to resolve this situation,
1738/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001739///
1740/// In C++, New and Old must be declarations that are not
1741/// overloaded. Use IsOverload to determine whether New and Old are
1742/// overloaded, and to select the Old declaration that New should be
1743/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00001744///
1745/// Returns true if there was an error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +00001746bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00001748 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001749 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00001750 = dyn_cast<FunctionTemplateDecl>(OldD))
1751 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001752 else
Douglas Gregore53060f2009-06-25 22:08:12 +00001753 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00001755 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1756 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1757 Diag(Shadow->getTargetDecl()->getLocation(),
1758 diag::note_using_decl_target);
1759 Diag(Shadow->getUsingDecl()->getLocation(),
1760 diag::note_using_decl) << 0;
1761 return true;
1762 }
1763
Chris Lattner5dc266a2008-11-20 06:13:02 +00001764 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001765 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001766 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00001767 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001769
1770 // Determine whether the previous declaration was a definition,
1771 // implicit declaration, or a declaration.
1772 diag::kind PrevDiag;
1773 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00001774 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001775 else if (Old->isImplicit())
1776 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001777 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00001778 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Chris Lattner8bcfc5b2008-04-06 23:10:54 +00001780 QualType OldQType = Context.getCanonicalType(Old->getType());
1781 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001783 // Don't complain about this if we're in GNU89 mode and the old function
1784 // is an extern inline function.
Douglas Gregor04495c82009-02-24 01:23:02 +00001785 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00001786 New->getStorageClass() == SC_Static &&
1787 Old->getStorageClass() != SC_Static &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001788 !canRedefineFunction(Old, getLangOpts())) {
1789 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00001790 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1791 Diag(Old->getLocation(), PrevDiag);
1792 } else {
1793 Diag(New->getLocation(), diag::err_static_non_static) << New;
1794 Diag(Old->getLocation(), PrevDiag);
1795 return true;
1796 }
Douglas Gregor04495c82009-02-24 01:23:02 +00001797 }
1798
John McCallf82b4e82010-02-04 05:44:44 +00001799 // If a function is first declared with a calling convention, but is
1800 // later declared or defined without one, the second decl assumes the
1801 // calling convention of the first.
1802 //
1803 // For the new decl, we have to look at the NON-canonical type to tell the
1804 // difference between a function that really doesn't have a calling
1805 // convention and one that is declared cdecl. That's because in
1806 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1807 // because it is the default calling convention.
1808 //
1809 // Note also that we DO NOT return at this point, because we still have
1810 // other tests to run.
John McCalle6a365d2010-12-19 02:44:49 +00001811 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallf82b4e82010-02-04 05:44:44 +00001812 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCalle6a365d2010-12-19 02:44:49 +00001813 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1814 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1815 bool RequiresAdjustment = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00001816 if (OldTypeInfo.getCC() != CC_Default &&
1817 NewTypeInfo.getCC() == CC_Default) {
John McCalle6a365d2010-12-19 02:44:49 +00001818 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1819 RequiresAdjustment = true;
Rafael Espindola264ba482010-03-30 20:24:48 +00001820 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1821 NewTypeInfo.getCC())) {
John McCallf82b4e82010-02-04 05:44:44 +00001822 // Calling conventions really aren't compatible, so complain.
John McCall04a67a62010-02-05 21:31:56 +00001823 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindola264ba482010-03-30 20:24:48 +00001824 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1825 << (OldTypeInfo.getCC() == CC_Default)
1826 << (OldTypeInfo.getCC() == CC_Default ? "" :
1827 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCall04a67a62010-02-05 21:31:56 +00001828 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallf82b4e82010-02-04 05:44:44 +00001829 return true;
1830 }
1831
John McCall04a67a62010-02-05 21:31:56 +00001832 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00001833 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1834 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1835 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00001836 }
1837
Douglas Gregord2c64902010-06-18 21:30:25 +00001838 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00001839 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1840 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1841 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00001842 Diag(New->getLocation(), diag::err_regparm_mismatch)
1843 << NewType->getRegParmType()
1844 << OldType->getRegParmType();
1845 Diag(Old->getLocation(), diag::note_previous_declaration);
1846 return true;
1847 }
John McCalle6a365d2010-12-19 02:44:49 +00001848
1849 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1850 RequiresAdjustment = true;
1851 }
1852
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00001853 // Merge ns_returns_retained attribute.
1854 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1855 if (NewTypeInfo.getProducesResult()) {
1856 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1857 Diag(Old->getLocation(), diag::note_previous_declaration);
1858 return true;
1859 }
1860
1861 NewTypeInfo = NewTypeInfo.withProducesResult(true);
1862 RequiresAdjustment = true;
1863 }
1864
John McCalle6a365d2010-12-19 02:44:49 +00001865 if (RequiresAdjustment) {
1866 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1867 New->setType(QualType(NewType, 0));
1868 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregord2c64902010-06-18 21:30:25 +00001869 }
1870
David Blaikie4e4d0842012-03-11 07:00:24 +00001871 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001872 // (C++98 13.1p2):
1873 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00001874 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001875 // cannot be overloaded.
John McCalle6a365d2010-12-19 02:44:49 +00001876 QualType OldReturnType = OldType->getResultType();
1877 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001878 QualType ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001879 if (OldReturnType != NewReturnType) {
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001880 if (NewReturnType->isObjCObjectPointerType()
1881 && OldReturnType->isObjCObjectPointerType())
1882 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1883 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00001884 if (New->isCXXClassMember() && New->isOutOfLine())
1885 Diag(New->getLocation(),
1886 diag::err_member_def_does_not_match_ret_type) << New;
1887 else
1888 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001889 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1890 return true;
1891 }
1892 else
1893 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001894 }
1895
1896 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall3d043362010-04-13 07:45:41 +00001897 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001898 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00001899 // Preserve triviality.
1900 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00001901
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001902 // MSVC allows explicit template specialization at class scope:
1903 // 2 CXMethodDecls referring to the same function will be injected.
1904 // We don't want a redeclartion error.
1905 bool IsClassScopeExplicitSpecialization =
1906 OldMethod->isFunctionTemplateSpecialization() &&
1907 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00001908 bool isFriend = NewMethod->getFriendObjectKind();
1909
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001910 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1911 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001912 // -- Member function declarations with the same name and the
1913 // same parameter types cannot be overloaded if any of them
1914 // is a static member function declaration.
1915 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1916 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1917 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1918 return true;
1919 }
1920
1921 // C++ [class.mem]p1:
1922 // [...] A member shall not be declared twice in the
1923 // member-specification, except that a nested class or member
1924 // class template can be declared and then later defined.
1925 unsigned NewDiag;
1926 if (isa<CXXConstructorDecl>(OldMethod))
1927 NewDiag = diag::err_constructor_redeclared;
1928 else if (isa<CXXDestructorDecl>(NewMethod))
1929 NewDiag = diag::err_destructor_redeclared;
1930 else if (isa<CXXConversionDecl>(NewMethod))
1931 NewDiag = diag::err_conv_function_redeclared;
1932 else
1933 NewDiag = diag::err_member_redeclared;
1934
1935 Diag(New->getLocation(), NewDiag);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001936 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00001937
1938 // Complain if this is an explicit declaration of a special
1939 // member that was initially declared implicitly.
1940 //
1941 // As an exception, it's okay to befriend such methods in order
1942 // to permit the implicit constructor/destructor/operator calls.
1943 } else if (OldMethod->isImplicit()) {
1944 if (isFriend) {
1945 NewMethod->setImplicit();
1946 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001947 Diag(NewMethod->getLocation(),
1948 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001949 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001950 return true;
1951 }
Sean Hunt001cad92011-05-10 00:49:42 +00001952 } else if (OldMethod->isExplicitlyDefaulted()) {
1953 Diag(NewMethod->getLocation(),
1954 diag::err_definition_of_explicitly_defaulted_member)
1955 << getSpecialMember(OldMethod);
1956 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001957 }
1958 }
1959
1960 // (C++98 8.3.5p3):
1961 // All declarations for a function shall agree exactly in both the
1962 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00001963 // We also want to respect all the extended bits except noreturn.
1964
1965 // noreturn should now match unless the old type info didn't have it.
1966 QualType OldQTypeForComparison = OldQType;
1967 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1968 assert(OldQType == QualType(OldType, 0));
1969 const FunctionType *OldTypeForComparison
1970 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1971 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1972 assert(OldQTypeForComparison.isCanonical());
1973 }
1974
1975 if (OldQTypeForComparison == NewQType)
James Molloy9cda03f2012-03-13 08:55:35 +00001976 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001977
1978 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00001979 }
Chris Lattner04421082008-04-08 04:40:51 +00001980
1981 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001982 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00001983 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00001984 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00001985 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1986 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001987 const FunctionProtoType *OldProto = 0;
1988 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001989 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00001990 // The old declaration provided a function prototype, but the
1991 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00001992 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001993 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00001994 OldProto->arg_type_end());
1995 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001996 ParamTypes.data(), ParamTypes.size(),
John McCalle23cf432010-12-14 08:05:40 +00001997 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00001998 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00001999 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002000
2001 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002002 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002003 for (FunctionProtoType::arg_type_iterator
2004 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002005 ParamEnd = OldProto->arg_type_end();
2006 ParamType != ParamEnd; ++ParamType) {
2007 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002008 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002009 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002010 *ParamType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00002011 SC_None, SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002012 0);
John McCallfb44de92011-05-01 22:35:37 +00002013 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002014 Param->setImplicit();
2015 Params.push_back(Param);
2016 }
2017
David Blaikie4278c652011-09-21 18:16:56 +00002018 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002019 }
Douglas Gregor68719812009-02-16 18:20:44 +00002020
James Molloy9cda03f2012-03-13 08:55:35 +00002021 return MergeCompatibleFunctionDecls(New, Old, S);
Chris Lattner04421082008-04-08 04:40:51 +00002022 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002023
Douglas Gregorc8376562009-03-06 22:43:54 +00002024 // GNU C permits a K&R definition to follow a prototype declaration
2025 // if the declared types of the parameters in the K&R definition
2026 // match the types in the prototype declaration, even when the
2027 // promoted types of the parameters from the K&R definition differ
2028 // from the types in the prototype. GCC then keeps the types from
2029 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002030 //
2031 // If a variadic prototype is followed by a non-variadic K&R definition,
2032 // the K&R definition becomes variadic. This is sort of an edge case, but
2033 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2034 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002035 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002036 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002037 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002038 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002039 SmallVector<QualType, 16> ArgTypes;
2040 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002041 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002042 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002043 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002044 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Douglas Gregorc8376562009-03-06 22:43:54 +00002046 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002047 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2048 NewProto->getResultType());
2049 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002050 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002051 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002052 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2053 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002054 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002055 NewProto->getArgType(Idx))) {
2056 ArgTypes.push_back(NewParm->getType());
2057 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002058 NewParm->getType(),
2059 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002060 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002061 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2062 Warnings.push_back(Warn);
2063 ArgTypes.push_back(NewParm->getType());
2064 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002065 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002066 }
2067
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002068 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002069 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2070 Diag(Warnings[Warn].NewParm->getLocation(),
2071 diag::ext_param_promoted_not_compatible_with_prototype)
2072 << Warnings[Warn].PromotedType
2073 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002074 if (Warnings[Warn].OldParm->getLocation().isValid())
2075 Diag(Warnings[Warn].OldParm->getLocation(),
2076 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002077 }
2078
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002079 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2080 ArgTypes.size(),
John McCalle23cf432010-12-14 08:05:40 +00002081 OldProto->getExtProtoInfo()));
James Molloy9cda03f2012-03-13 08:55:35 +00002082 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregorc8376562009-03-06 22:43:54 +00002083 }
2084
2085 // Fall through to diagnose conflicting types.
2086 }
2087
Steve Naroff837618c2008-01-16 15:01:34 +00002088 // A function that has already been declared has been redeclared or defined
2089 // with a different type- show appropriate diagnostic
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002090 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002091 // The user has declared a builtin function with an incompatible
2092 // signature.
2093 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2094 // The function the user is redeclaring is a library-defined
2095 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor374e1562009-03-23 17:47:24 +00002096 // redeclaration, then pretend that we don't know about this
2097 // library built-in.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002098 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2099 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2100 << Old << Old->getType();
Douglas Gregor374e1562009-03-23 17:47:24 +00002101 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2102 Old->setInvalidDecl();
2103 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002104 }
Steve Naroff837618c2008-01-16 15:01:34 +00002105
Douglas Gregorcda9c672009-02-16 17:45:42 +00002106 PrevDiag = diag::note_previous_builtin_declaration;
2107 }
2108
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002109 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002110 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002111 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002112}
2113
Douglas Gregor04495c82009-02-24 01:23:02 +00002114/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002115/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002116///
2117/// This routine handles the merging of attributes and other
2118/// properties of function declarations form the old declaration to
2119/// the new declaration, once we know that New is in fact a
2120/// redeclaration of Old.
2121///
2122/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002123bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2124 Scope *S) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002125 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002126 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002127
2128 // Merge the storage class.
John McCalld931b082010-08-26 03:08:43 +00002129 if (Old->getStorageClass() != SC_Extern &&
2130 Old->getStorageClass() != SC_None)
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002131 New->setStorageClass(Old->getStorageClass());
Douglas Gregor04495c82009-02-24 01:23:02 +00002132
Douglas Gregor04495c82009-02-24 01:23:02 +00002133 // Merge "pure" flag.
2134 if (Old->isPure())
2135 New->setPure();
2136
John McCalleca5d222011-03-02 04:00:57 +00002137 // Merge attributes from the parameters. These can mismatch with K&R
2138 // declarations.
2139 if (New->getNumParams() == Old->getNumParams())
2140 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2141 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2142 Context);
2143
David Blaikie4e4d0842012-03-11 07:00:24 +00002144 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002145 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002146
2147 return false;
2148}
2149
John McCallf85e1932011-06-15 23:02:42 +00002150
John McCalleca5d222011-03-02 04:00:57 +00002151void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002152 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002153 // We don't want to merge unavailable and deprecated attributes
2154 // except from interface to implementation.
2155 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2156
John McCalleca5d222011-03-02 04:00:57 +00002157 // Merge the attributes.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002158 mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
John McCalleca5d222011-03-02 04:00:57 +00002159
2160 // Merge attributes from the parameters.
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002161 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2162 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002163 ni = newMethod->param_begin(), ne = newMethod->param_end();
2164 ni != ne; ++ni, ++oi)
Douglas Gregor926df6c2011-06-11 01:09:30 +00002165 mergeParamDeclAttributes(*ni, *oi, Context);
John McCall6c2c2502011-07-22 02:45:48 +00002166
Douglas Gregor926df6c2011-06-11 01:09:30 +00002167 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCalleca5d222011-03-02 04:00:57 +00002168}
2169
Sebastian Redl60618fa2011-03-12 11:50:43 +00002170/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2171/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002172/// emitting diagnostics as appropriate.
2173///
2174/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002175/// to here in AddInitializerToDecl. We can't check them before the initializer
2176/// is attached.
Richard Smith34b41d92011-02-20 03:19:35 +00002177void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2178 if (New->isInvalidDecl() || Old->isInvalidDecl())
2179 return;
2180
2181 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002182 if (getLangOpts().CPlusPlus) {
Richard Smith34b41d92011-02-20 03:19:35 +00002183 AutoType *AT = New->getType()->getContainedAutoType();
2184 if (AT && !AT->isDeduced()) {
2185 // We don't know what the new type is until the initializer is attached.
2186 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002187 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2188 // These could still be something that needs exception specs checked.
2189 return MergeVarDeclExceptionSpecs(New, Old);
2190 }
Richard Smith34b41d92011-02-20 03:19:35 +00002191 // C++ [basic.link]p10:
2192 // [...] the types specified by all declarations referring to a given
2193 // object or function shall be identical, except that declarations for an
2194 // array object can specify array types that differ by the presence or
2195 // absence of a major array bound (8.3.4).
2196 else if (Old->getType()->isIncompleteArrayType() &&
2197 New->getType()->isArrayType()) {
2198 CanQual<ArrayType> OldArray
2199 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2200 CanQual<ArrayType> NewArray
2201 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2202 if (OldArray->getElementType() == NewArray->getElementType())
2203 MergedT = New->getType();
2204 } else if (Old->getType()->isArrayType() &&
2205 New->getType()->isIncompleteArrayType()) {
2206 CanQual<ArrayType> OldArray
2207 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2208 CanQual<ArrayType> NewArray
2209 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2210 if (OldArray->getElementType() == NewArray->getElementType())
2211 MergedT = Old->getType();
2212 } else if (New->getType()->isObjCObjectPointerType()
2213 && Old->getType()->isObjCObjectPointerType()) {
2214 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2215 Old->getType());
2216 }
2217 } else {
2218 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2219 }
2220 if (MergedT.isNull()) {
2221 Diag(New->getLocation(), diag::err_redefinition_different_type)
2222 << New->getDeclName();
2223 Diag(Old->getLocation(), diag::note_previous_definition);
2224 return New->setInvalidDecl();
2225 }
2226 New->setType(MergedT);
2227}
2228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2230/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2231/// situation, merging decls or emitting diagnostics as appropriate.
2232///
Mike Stump1eb44332009-09-09 15:08:12 +00002233/// Tentative definition rules (C99 6.9.2p2) are checked by
2234/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002235/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00002236///
John McCall68263142009-11-18 22:49:29 +00002237void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2238 // If the new decl is already invalid, don't do any other checking.
2239 if (New->isInvalidDecl())
2240 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 // Verify the old decl was also a variable.
John McCall68263142009-11-18 22:49:29 +00002243 VarDecl *Old = 0;
2244 if (!Previous.isSingleResult() ||
2245 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002246 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002247 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00002248 Diag(Previous.getRepresentativeDecl()->getLocation(),
2249 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002250 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 }
Chris Lattnerddee4232008-03-03 03:28:21 +00002252
Douglas Gregor7f6ff022010-08-30 14:32:14 +00002253 // C++ [class.mem]p1:
2254 // A member shall not be declared twice in the member-specification [...]
2255 //
2256 // Here, we need only consider static data members.
2257 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2258 Diag(New->getLocation(), diag::err_duplicate_member)
2259 << New->getIdentifier();
2260 Diag(Old->getLocation(), diag::note_previous_declaration);
2261 New->setInvalidDecl();
2262 }
2263
Douglas Gregor27c6da22012-01-01 20:30:41 +00002264 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00002265 // Warn if an already-declared variable is made a weak_import in a subsequent
2266 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00002267 if (New->getAttr<WeakImportAttr>() &&
2268 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00002269 !Old->getAttr<WeakImportAttr>()) {
2270 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2271 Diag(Old->getLocation(), diag::note_previous_definition);
2272 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00002273 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00002274 }
Chris Lattnerddee4232008-03-03 03:28:21 +00002275
Richard Smith34b41d92011-02-20 03:19:35 +00002276 // Merge the types.
2277 MergeVarDeclTypes(New, Old);
2278 if (New->isInvalidDecl())
2279 return;
Douglas Gregor656de632009-03-11 23:52:16 +00002280
Steve Naroffb7b032e2008-01-30 00:44:01 +00002281 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCalld931b082010-08-26 03:08:43 +00002282 if (New->getStorageClass() == SC_Static &&
2283 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002284 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002285 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002286 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00002287 }
Mike Stump1eb44332009-09-09 15:08:12 +00002288 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00002289 // For an identifier declared with the storage-class specifier
2290 // extern in a scope in which a prior declaration of that
2291 // identifier is visible,23) if the prior declaration specifies
2292 // internal or external linkage, the linkage of the identifier at
2293 // the later declaration is the same as the linkage specified at
2294 // the prior declaration. If no prior declaration is visible, or
2295 // if the prior declaration specifies no linkage, then the
2296 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00002297 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00002298 /* Okay */;
John McCalld931b082010-08-26 03:08:43 +00002299 else if (New->getStorageClass() != SC_Static &&
2300 Old->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002301 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002302 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002303 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00002304 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00002305
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00002306 // Check if extern is followed by non-extern and vice-versa.
2307 if (New->hasExternalStorage() &&
2308 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2309 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2310 Diag(Old->getLocation(), diag::note_previous_definition);
2311 return New->setInvalidDecl();
2312 }
2313 if (Old->hasExternalStorage() &&
2314 !New->hasLinkage() && New->isLocalVarDecl()) {
2315 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2316 Diag(Old->getLocation(), diag::note_previous_definition);
2317 return New->setInvalidDecl();
2318 }
2319
Steve Naroff094cefb2008-09-17 14:05:40 +00002320 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00002322 // FIXME: The test for external storage here seems wrong? We still
2323 // need to check for mismatches.
2324 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00002325 // Don't complain about out-of-line definitions of static members.
2326 !(Old->getLexicalDeclContext()->isRecord() &&
2327 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00002328 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002329 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002330 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 }
Douglas Gregor275a3692009-03-10 23:43:53 +00002332
Eli Friedman63054b32009-04-19 20:27:55 +00002333 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2334 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2335 Diag(Old->getLocation(), diag::note_previous_definition);
2336 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2337 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2338 Diag(Old->getLocation(), diag::note_previous_definition);
2339 }
2340
Sebastian Redl4cae1b32010-02-02 18:35:11 +00002341 // C++ doesn't have tentative definitions, so go right ahead and check here.
2342 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00002343 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00002344 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00002345 (Def = Old->getDefinition())) {
2346 Diag(New->getLocation(), diag::err_redefinition)
2347 << New->getDeclName();
2348 Diag(Def->getLocation(), diag::note_previous_definition);
2349 New->setInvalidDecl();
2350 return;
2351 }
Fariborz Jahanianfba9e8f2010-06-25 00:05:45 +00002352 // c99 6.2.2 P4.
2353 // For an identifier declared with the storage-class specifier extern in a
2354 // scope in which a prior declaration of that identifier is visible, if
2355 // the prior declaration specifies internal or external linkage, the linkage
2356 // of the identifier at the later declaration is the same as the linkage
2357 // specified at the prior declaration.
2358 // FIXME. revisit this code.
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00002359 if (New->hasExternalStorage() &&
Fariborz Jahanian7d99e982010-06-24 18:50:41 +00002360 Old->getLinkage() == InternalLinkage &&
2361 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00002362 New->setStorageClass(Old->getStorageClass());
2363
Douglas Gregor275a3692009-03-10 23:43:53 +00002364 // Keep a chain of previous declarations.
2365 New->setPreviousDeclaration(Old);
John McCall46460a62010-01-20 21:53:11 +00002366
2367 // Inherit access appropriately.
2368 New->setAccess(Old->getAccess());
Reid Spencer5f016e22007-07-11 17:01:13 +00002369}
2370
2371/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2372/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00002373Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00002374 DeclSpec &DS) {
Chandler Carruth0f4be742011-05-03 18:35:10 +00002375 return ParsedFreeStandingDeclSpec(S, AS, DS,
2376 MultiTemplateParamsArg(*this, 0, 0));
2377}
2378
2379/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2380/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2381/// parameters to cope with template friend declarations.
2382Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2383 DeclSpec &DS,
2384 MultiTemplateParamsArg TemplateParams) {
John McCalle3af0232009-10-07 23:34:25 +00002385 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002386 TagDecl *Tag = 0;
2387 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2388 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2389 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00002390 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00002391 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00002392
2393 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00002394 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00002395
John McCall67d1a672009-08-06 02:15:43 +00002396 // Note that the above type specs guarantee that the
2397 // type rep is a Decl, whereas in many of the others
2398 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00002399 if (isa<TagDecl>(TagD))
2400 Tag = cast<TagDecl>(TagD);
2401 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2402 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00002403 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002404
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00002405 if (Tag) {
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00002406 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00002407 if (Tag->isInvalidDecl())
2408 return Tag;
2409 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00002410
Nuno Lopes0a8bab02009-12-17 11:35:26 +00002411 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2412 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2413 // or incomplete types shall not be restrict-qualified."
2414 if (TypeQuals & DeclSpec::TQ_restrict)
2415 Diag(DS.getRestrictSpecLoc(),
2416 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2417 << DS.getSourceRange();
2418 }
2419
Richard Smithaf1fc7a2011-08-15 21:04:07 +00002420 if (DS.isConstexprSpecified()) {
2421 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2422 // and definitions of functions and variables.
2423 if (Tag)
2424 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2425 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2426 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2427 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2428 else
2429 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2430 // Don't emit warnings after this error.
2431 return TagD;
2432 }
2433
Douglas Gregord85bea22009-09-26 06:47:28 +00002434 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00002435 // If we're dealing with a decl but not a TagDecl, assume that
2436 // whatever routines created it handled the friendship aspect.
2437 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00002438 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00002439 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00002440 }
John McCallac4df242011-03-22 23:00:04 +00002441
2442 // Track whether we warned about the fact that there aren't any
2443 // declarators.
2444 bool emittedWarning = false;
Douglas Gregord85bea22009-09-26 06:47:28 +00002445
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002446 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00002447 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00002448 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002449 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00002450 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00002451 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00002452
Daniel Dunbar96a00142012-03-09 18:35:03 +00002453 Diag(DS.getLocStart(), diag::ext_no_declarators)
Douglas Gregora71c1292009-03-06 23:06:59 +00002454 << DS.getSourceRange();
John McCallac4df242011-03-22 23:00:04 +00002455 emittedWarning = true;
Douglas Gregora71c1292009-03-06 23:06:59 +00002456 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00002457 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002458
Francois Pichet8e161ed2010-11-23 06:07:27 +00002459 // Check for Microsoft C extension: anonymous struct.
David Blaikie4e4d0842012-03-11 07:00:24 +00002460 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00002461 CurContext->isRecord() &&
2462 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2463 // Handle 2 kinds of anonymous struct:
2464 // struct STRUCT;
2465 // and
2466 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2467 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00002468 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00002469 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2470 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002471 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00002472 << DS.getSourceRange();
2473 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2474 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002475 }
Douglas Gregord85bea22009-09-26 06:47:28 +00002476
David Blaikie4e4d0842012-03-11 07:00:24 +00002477 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00002478 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2479 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2480 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallac4df242011-03-22 23:00:04 +00002481 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregora131d0f2010-07-13 06:24:26 +00002482 Diag(Enum->getLocation(), diag::ext_no_declarators)
2483 << DS.getSourceRange();
John McCallac4df242011-03-22 23:00:04 +00002484 emittedWarning = true;
2485 }
2486
2487 // Skip all the checks below if we have a type error.
2488 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregora131d0f2010-07-13 06:24:26 +00002489
John McCallac4df242011-03-22 23:00:04 +00002490 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor21282df2009-01-22 16:23:54 +00002491 // Warn about typedefs of enums without names, since this is an
Douglas Gregora0ebd602010-07-16 15:40:40 +00002492 // extension in both Microsoft and GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +00002493 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2494 Tag && isa<EnumDecl>(Tag)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002495 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00002496 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00002497 return Tag;
Douglas Gregoree159c12009-01-13 23:10:51 +00002498 }
2499
Daniel Dunbar96a00142012-03-09 18:35:03 +00002500 Diag(DS.getLocStart(), diag::ext_no_declarators)
Sebastian Redla4ed0d82008-12-28 15:28:59 +00002501 << DS.getSourceRange();
John McCallac4df242011-03-22 23:00:04 +00002502 emittedWarning = true;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00002503 }
Mike Stump1eb44332009-09-09 15:08:12 +00002504
John McCallac4df242011-03-22 23:00:04 +00002505 // We're going to complain about a bunch of spurious specifiers;
2506 // only do this if we're declaring a tag, because otherwise we
2507 // should be getting diag::ext_no_declarators.
2508 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2509 return TagD;
2510
John McCall379246d2011-03-26 02:09:52 +00002511 // Note that a linkage-specification sets a storage class, but
2512 // 'extern "C" struct foo;' is actually valid and not theoretically
2513 // useless.
John McCallac4df242011-03-22 23:00:04 +00002514 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall379246d2011-03-26 02:09:52 +00002515 if (!DS.isExternInLinkageSpec())
2516 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2517 << DeclSpec::getSpecifierName(scs);
2518
John McCallac4df242011-03-22 23:00:04 +00002519 if (DS.isThreadSpecified())
2520 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2521 if (DS.getTypeQualifiers()) {
2522 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2523 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2524 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2525 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2526 // Restrict is covered above.
2527 }
2528 if (DS.isInlineSpecified())
2529 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2530 if (DS.isVirtualSpecified())
2531 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2532 if (DS.isExplicitSpecified())
2533 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2534
Douglas Gregore3895852011-09-12 18:37:38 +00002535 if (DS.isModulePrivateSpecified() &&
2536 Tag && Tag->getDeclContext()->isFunctionOrMethod())
2537 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2538 << Tag->getTagKind()
2539 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2540
Eli Friedmanfc038e92011-12-17 00:36:09 +00002541 // Warn about ignored type attributes, for example:
2542 // __attribute__((aligned)) struct A;
2543 // Attributes should be placed after tag to apply to type declaration.
2544 if (!DS.getAttributes().empty()) {
2545 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2546 if (TypeSpecType == DeclSpec::TST_class ||
2547 TypeSpecType == DeclSpec::TST_struct ||
2548 TypeSpecType == DeclSpec::TST_union ||
2549 TypeSpecType == DeclSpec::TST_enum) {
2550 AttributeList* attrs = DS.getAttributes().getList();
2551 while (attrs) {
2552 Diag(attrs->getScopeLoc(),
2553 diag::warn_declspec_attribute_ignored)
2554 << attrs->getName()
2555 << (TypeSpecType == DeclSpec::TST_class ? 0 :
2556 TypeSpecType == DeclSpec::TST_struct ? 1 :
2557 TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2558 attrs = attrs->getNext();
2559 }
2560 }
2561 }
John McCallac4df242011-03-22 23:00:04 +00002562
John McCalld226f652010-08-21 09:40:31 +00002563 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002564}
2565
John McCall1d7c5282009-12-18 10:40:03 +00002566/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00002567/// check if there's an existing declaration that can't be overloaded.
2568///
2569/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00002570static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2571 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00002572 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00002573 DeclarationName Name,
2574 SourceLocation NameLoc,
2575 unsigned diagnostic) {
2576 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2577 Sema::ForRedeclaration);
2578 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00002579
John McCall1d7c5282009-12-18 10:40:03 +00002580 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00002581 return false;
2582
2583 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00002584 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00002585 assert(PrevDecl && "Expected a non-null Decl");
2586
2587 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2588 return false;
John McCall68263142009-11-18 22:49:29 +00002589
John McCall1d7c5282009-12-18 10:40:03 +00002590 SemaRef.Diag(NameLoc, diagnostic) << Name;
2591 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00002592
2593 return true;
2594}
2595
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002596/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2597/// anonymous struct or union AnonRecord into the owning context Owner
2598/// and scope S. This routine will be invoked just after we realize
2599/// that an unnamed union or struct is actually an anonymous union or
2600/// struct, e.g.,
2601///
2602/// @code
2603/// union {
2604/// int i;
2605/// float f;
2606/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2607/// // f into the surrounding scope.x
2608/// @endcode
2609///
2610/// This routine is recursive, injecting the names of nested anonymous
2611/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00002612static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2613 DeclContext *Owner,
2614 RecordDecl *AnonRecord,
Francois Pichet87c2e122010-11-21 06:08:52 +00002615 AccessSpecifier AS,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002616 SmallVector<NamedDecl*, 2> &Chaining,
Francois Pichet8e161ed2010-11-23 06:07:27 +00002617 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00002618 unsigned diagKind
2619 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2620 : diag::err_anonymous_struct_member_redecl;
2621
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002622 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00002623
2624 // Look every FieldDecl and IndirectFieldDecl with a name.
2625 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2626 DEnd = AnonRecord->decls_end();
2627 D != DEnd; ++D) {
2628 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2629 cast<NamedDecl>(*D)->getDeclName()) {
2630 ValueDecl *VD = cast<ValueDecl>(*D);
2631 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2632 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002633 // C++ [class.union]p2:
2634 // The names of the members of an anonymous union shall be
2635 // distinct from the names of any other entity in the
2636 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002637 Invalid = true;
2638 } else {
2639 // C++ [class.union]p2:
2640 // For the purpose of name lookup, after the anonymous union
2641 // definition, the members of the anonymous union are
2642 // considered to have been defined in the scope in which the
2643 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00002644 unsigned OldChainingSize = Chaining.size();
2645 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2646 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2647 PE = IF->chain_end(); PI != PE; ++PI)
2648 Chaining.push_back(*PI);
2649 else
2650 Chaining.push_back(VD);
2651
Francois Pichet87c2e122010-11-21 06:08:52 +00002652 assert(Chaining.size() >= 2);
2653 NamedDecl **NamedChain =
2654 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2655 for (unsigned i = 0; i < Chaining.size(); i++)
2656 NamedChain[i] = Chaining[i];
2657
2658 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00002659 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2660 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00002661 NamedChain, Chaining.size());
2662
2663 IndirectField->setAccess(AS);
2664 IndirectField->setImplicit();
2665 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00002666
2667 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00002668 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00002669
Francois Pichet8e161ed2010-11-23 06:07:27 +00002670 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002671 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002672 }
2673 }
2674
2675 return Invalid;
2676}
2677
Douglas Gregor16573fa2010-04-19 22:54:31 +00002678/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2679/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00002680/// illegal input values are mapped to SC_None.
2681static StorageClass
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002682StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00002683 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00002684 case DeclSpec::SCS_unspecified: return SC_None;
2685 case DeclSpec::SCS_extern: return SC_Extern;
2686 case DeclSpec::SCS_static: return SC_Static;
2687 case DeclSpec::SCS_auto: return SC_Auto;
2688 case DeclSpec::SCS_register: return SC_Register;
2689 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00002690 // Illegal SCSs map to None: error reporting is up to the caller.
2691 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00002692 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00002693 }
2694 llvm_unreachable("unknown storage class specifier");
2695}
2696
2697/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCalld931b082010-08-26 03:08:43 +00002698/// a StorageClass. Any error reporting is up to the caller:
2699/// illegal input values are mapped to SC_None.
2700static StorageClass
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002701StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00002702 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00002703 case DeclSpec::SCS_unspecified: return SC_None;
2704 case DeclSpec::SCS_extern: return SC_Extern;
2705 case DeclSpec::SCS_static: return SC_Static;
2706 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00002707 // Illegal SCSs map to None: error reporting is up to the caller.
2708 case DeclSpec::SCS_auto: // Fall through.
2709 case DeclSpec::SCS_mutable: // Fall through.
2710 case DeclSpec::SCS_register: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00002711 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00002712 }
2713 llvm_unreachable("unknown storage class specifier");
2714}
2715
Francois Pichet8e161ed2010-11-23 06:07:27 +00002716/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002717/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00002718/// (C++ [class.union]) and a C11 feature; anonymous structures
2719/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00002720Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2721 AccessSpecifier AS,
2722 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002723 DeclContext *Owner = Record->getDeclContext();
2724
2725 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00002726 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002727 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00002728 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00002729 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00002730 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00002731 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002733 // C and C++ require different kinds of checks for anonymous
2734 // structs/unions.
2735 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00002736 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002737 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00002738 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00002739 if (Record->isUnion()) {
2740 // C++ [class.union]p6:
2741 // Anonymous unions declared in a named namespace or in the
2742 // global namespace shall be declared static.
2743 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2744 (isa<TranslationUnitDecl>(Owner) ||
2745 (isa<NamespaceDecl>(Owner) &&
2746 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00002747 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2748 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00002749
2750 // Recover by adding 'static'.
2751 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2752 PrevSpec, DiagID);
2753 }
2754 // C++ [class.union]p6:
2755 // A storage class is not allowed in a declaration of an
2756 // anonymous union in a class scope.
2757 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2758 isa<RecordDecl>(Owner)) {
2759 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00002760 diag::err_anonymous_union_with_storage_spec)
2761 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00002762
2763 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00002764 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
2765 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00002766 PrevSpec, DiagID);
2767 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002768 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002769
Douglas Gregor7604f642011-05-09 23:05:33 +00002770 // Ignore const/volatile/restrict qualifiers.
2771 if (DS.getTypeQualifiers()) {
2772 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2773 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2774 << Record->isUnion() << 0
2775 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2776 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
David Blaikied662a792011-10-19 22:56:21 +00002777 Diag(DS.getVolatileSpecLoc(),
2778 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor7604f642011-05-09 23:05:33 +00002779 << Record->isUnion() << 1
2780 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2781 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
David Blaikied662a792011-10-19 22:56:21 +00002782 Diag(DS.getRestrictSpecLoc(),
2783 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor7604f642011-05-09 23:05:33 +00002784 << Record->isUnion() << 2
2785 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2786
2787 DS.ClearTypeQualifiers();
2788 }
2789
Mike Stump1eb44332009-09-09 15:08:12 +00002790 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002791 // The member-specification of an anonymous union shall only
2792 // define non-static data members. [Note: nested types and
2793 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002794 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2795 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002796 Mem != MemEnd; ++Mem) {
2797 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2798 // C++ [class.union]p3:
2799 // An anonymous union shall not have private or protected
2800 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00002801 assert(FD->getAccess() != AS_none);
2802 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002803 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2804 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2805 Invalid = true;
2806 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00002807
Sean Huntcf34e752011-05-16 22:41:40 +00002808 // C++ [class.union]p1
2809 // An object of a class with a non-trivial constructor, a non-trivial
2810 // copy constructor, a non-trivial destructor, or a non-trivial copy
2811 // assignment operator cannot be a member of a union, nor can an
2812 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00002813 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00002814 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002815 } else if ((*Mem)->isImplicit()) {
2816 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00002817 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2818 // This is a type that showed up in an
2819 // elaborated-type-specifier inside the anonymous struct or
2820 // union, but which actually declares a type outside of the
2821 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002822 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2823 if (!MemRecord->isAnonymousStructOrUnion() &&
2824 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00002825 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00002826 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00002827 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2828 << (int)Record->isUnion();
2829 else {
2830 // This is a nested type declaration.
2831 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2832 << (int)Record->isUnion();
2833 Invalid = true;
2834 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002835 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00002836 } else if (isa<AccessSpecDecl>(*Mem)) {
2837 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002838 } else {
2839 // We have something that isn't a non-static data
2840 // member. Complain about it.
2841 unsigned DK = diag::err_anonymous_record_bad_member;
2842 if (isa<TypeDecl>(*Mem))
2843 DK = diag::err_anonymous_record_with_type;
2844 else if (isa<FunctionDecl>(*Mem))
2845 DK = diag::err_anonymous_record_with_function;
2846 else if (isa<VarDecl>(*Mem))
2847 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00002848
2849 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00002850 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00002851 DK == diag::err_anonymous_record_with_type)
2852 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002853 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00002854 else {
2855 Diag((*Mem)->getLocation(), DK)
2856 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002857 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00002858 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002859 }
2860 }
Mike Stump1eb44332009-09-09 15:08:12 +00002861 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002862
2863 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002864 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00002865 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002866 Invalid = true;
2867 }
2868
John McCalleb692e02009-10-22 23:31:08 +00002869 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002870 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00002871 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00002872 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00002873
Mike Stump1eb44332009-09-09 15:08:12 +00002874 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002875 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002876 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002877 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00002878 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002879 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002880 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002881 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00002882 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00002883 /*BitWidth=*/0, /*Mutable=*/false,
2884 /*HasInit=*/false);
John McCallaec03712010-05-21 20:45:30 +00002885 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00002886 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002887 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002888 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00002889 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2890 assert(SCSpec != DeclSpec::SCS_typedef &&
2891 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002892 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00002893 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002894 // mutable can only appear on non-static class members, so it's always
2895 // an error here
2896 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2897 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00002898 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002899 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00002900 SCSpec = DS.getStorageClassSpecAsWritten();
2901 VarDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002902 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002903
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002904 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00002905 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002906 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002907 Context.getTypeDeclType(Record),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002908 TInfo, SC, SCAsWritten);
Richard Smith16ee8192011-09-18 00:06:34 +00002909
2910 // Default-initialize the implicit variable. This initialization will be
2911 // trivial in almost all cases, except if a union member has an in-class
2912 // initializer:
2913 // union { int n = 0; };
2914 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002915 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002916 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002917
2918 // Add the anonymous struct/union object to the current
2919 // context. We'll be referencing this object when we refer to one of
2920 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002921 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00002922
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002923 // Inject the members of the anonymous struct/union into the owning
2924 // context and into the identifier resolver chain for name lookup
2925 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002926 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00002927 Chain.push_back(Anon);
2928
Francois Pichet8e161ed2010-11-23 06:07:27 +00002929 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2930 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002931 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002932
2933 // Mark this as an anonymous struct/union type. Note that we do not
2934 // do this until after we have already checked and injected the
2935 // members of this anonymous struct/union type, because otherwise
2936 // the members could be injected twice: once by DeclContext when it
2937 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00002938 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002939 Record->setAnonymousStructOrUnion(true);
2940
2941 if (Invalid)
2942 Anon->setInvalidDecl();
2943
John McCalld226f652010-08-21 09:40:31 +00002944 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002945}
2946
Francois Pichet8e161ed2010-11-23 06:07:27 +00002947/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2948/// Microsoft C anonymous structure.
2949/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2950/// Example:
2951///
2952/// struct A { int a; };
2953/// struct B { struct A; int b; };
2954///
2955/// void foo() {
2956/// B var;
2957/// var.a = 3;
2958/// }
2959///
2960Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2961 RecordDecl *Record) {
2962
2963 // If there is no Record, get the record via the typedef.
2964 if (!Record)
2965 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2966
2967 // Mock up a declarator.
2968 Declarator Dc(DS, Declarator::TypeNameContext);
2969 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2970 assert(TInfo && "couldn't build declarator info for anonymous struct");
2971
2972 // Create a declaration for this anonymous struct.
2973 NamedDecl* Anon = FieldDecl::Create(Context,
2974 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00002975 DS.getLocStart(),
2976 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00002977 /*IdentifierInfo=*/0,
2978 Context.getTypeDeclType(Record),
2979 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00002980 /*BitWidth=*/0, /*Mutable=*/false,
2981 /*HasInit=*/false);
Francois Pichet8e161ed2010-11-23 06:07:27 +00002982 Anon->setImplicit();
2983
2984 // Add the anonymous struct object to the current context.
2985 CurContext->addDecl(Anon);
2986
2987 // Inject the members of the anonymous struct into the current
2988 // context and into the identifier resolver chain for name lookup
2989 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002990 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00002991 Chain.push_back(Anon);
2992
Nico Weberee625af2012-02-01 00:41:00 +00002993 RecordDecl *RecordDef = Record->getDefinition();
2994 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2995 RecordDef, AS_none,
2996 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00002997 Anon->setInvalidDecl();
2998
2999 return Anon;
3000}
Steve Narofff0090632007-09-02 02:04:30 +00003001
Douglas Gregor10bd3682008-11-17 22:58:34 +00003002/// GetNameForDeclarator - Determine the full declaration name for the
3003/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003004DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003005 return GetNameFromUnqualifiedId(D.getName());
3006}
3007
Abramo Bagnara25777432010-08-11 22:01:17 +00003008/// \brief Retrieves the declaration name from a parsed unqualified-id.
3009DeclarationNameInfo
3010Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3011 DeclarationNameInfo NameInfo;
3012 NameInfo.setLoc(Name.StartLocation);
3013
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003014 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003015
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003016 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003017 case UnqualifiedId::IK_Identifier:
3018 NameInfo.setName(Name.Identifier);
3019 NameInfo.setLoc(Name.StartLocation);
3020 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003021
Abramo Bagnara25777432010-08-11 22:01:17 +00003022 case UnqualifiedId::IK_OperatorFunctionId:
3023 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3024 Name.OperatorFunctionId.Operator));
3025 NameInfo.setLoc(Name.StartLocation);
3026 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3027 = Name.OperatorFunctionId.SymbolLocations[0];
3028 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3029 = Name.EndLocation.getRawEncoding();
3030 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003031
Abramo Bagnara25777432010-08-11 22:01:17 +00003032 case UnqualifiedId::IK_LiteralOperatorId:
3033 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3034 Name.Identifier));
3035 NameInfo.setLoc(Name.StartLocation);
3036 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3037 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003038
Abramo Bagnara25777432010-08-11 22:01:17 +00003039 case UnqualifiedId::IK_ConversionFunctionId: {
3040 TypeSourceInfo *TInfo;
3041 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3042 if (Ty.isNull())
3043 return DeclarationNameInfo();
3044 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3045 Context.getCanonicalType(Ty)));
3046 NameInfo.setLoc(Name.StartLocation);
3047 NameInfo.setNamedTypeInfo(TInfo);
3048 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003049 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003050
3051 case UnqualifiedId::IK_ConstructorName: {
3052 TypeSourceInfo *TInfo;
3053 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3054 if (Ty.isNull())
3055 return DeclarationNameInfo();
3056 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3057 Context.getCanonicalType(Ty)));
3058 NameInfo.setLoc(Name.StartLocation);
3059 NameInfo.setNamedTypeInfo(TInfo);
3060 return NameInfo;
3061 }
3062
3063 case UnqualifiedId::IK_ConstructorTemplateId: {
3064 // In well-formed code, we can only have a constructor
3065 // template-id that refers to the current context, so go there
3066 // to find the actual type being constructed.
3067 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3068 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3069 return DeclarationNameInfo();
3070
3071 // Determine the type of the class being constructed.
3072 QualType CurClassType = Context.getTypeDeclType(CurClass);
3073
3074 // FIXME: Check two things: that the template-id names the same type as
3075 // CurClassType, and that the template-id does not occur when the name
3076 // was qualified.
3077
3078 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3079 Context.getCanonicalType(CurClassType)));
3080 NameInfo.setLoc(Name.StartLocation);
3081 // FIXME: should we retrieve TypeSourceInfo?
3082 NameInfo.setNamedTypeInfo(0);
3083 return NameInfo;
3084 }
3085
3086 case UnqualifiedId::IK_DestructorName: {
3087 TypeSourceInfo *TInfo;
3088 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3089 if (Ty.isNull())
3090 return DeclarationNameInfo();
3091 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3092 Context.getCanonicalType(Ty)));
3093 NameInfo.setLoc(Name.StartLocation);
3094 NameInfo.setNamedTypeInfo(TInfo);
3095 return NameInfo;
3096 }
3097
3098 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003099 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003100 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3101 return Context.getNameForTemplate(TName, TNameLoc);
3102 }
3103
3104 } // switch (Name.getKind())
3105
David Blaikieb219cfc2011-09-23 05:06:16 +00003106 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003107}
3108
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003109static QualType getCoreType(QualType Ty) {
3110 do {
3111 if (Ty->isPointerType() || Ty->isReferenceType())
3112 Ty = Ty->getPointeeType();
3113 else if (Ty->isArrayType())
3114 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3115 else
3116 return Ty.withoutLocalFastQualifiers();
3117 } while (true);
3118}
3119
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003120/// hasSimilarParameters - Determine whether the C++ functions Declaration
3121/// and Definition have "nearly" matching parameters. This heuristic is
3122/// used to improve diagnostics in the case where an out-of-line function
3123/// definition doesn't match any declaration within the class or namespace.
3124/// Also sets Params to the list of indices to the parameters that differ
3125/// between the declaration and the definition. If hasSimilarParameters
3126/// returns true and Params is empty, then all of the parameters match.
3127static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003128 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003129 FunctionDecl *Definition,
3130 llvm::SmallVectorImpl<unsigned> &Params) {
3131 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003132 if (Declaration->param_size() != Definition->param_size())
3133 return false;
3134 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3135 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3136 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3137
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003138 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003139 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003140 continue;
3141
3142 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3143 QualType DefParamBaseTy = getCoreType(DefParamTy);
3144 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3145 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3146
3147 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3148 (DeclTyName && DeclTyName == DefTyName))
3149 Params.push_back(Idx);
3150 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003151 return false;
3152 }
3153
3154 return true;
3155}
3156
John McCall63b43852010-04-29 23:50:39 +00003157/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3158/// declarator needs to be rebuilt in the current instantiation.
3159/// Any bits of declarator which appear before the name are valid for
3160/// consideration here. That's specifically the type in the decl spec
3161/// and the base type in any member-pointer chunks.
3162static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3163 DeclarationName Name) {
3164 // The types we specifically need to rebuild are:
3165 // - typenames, typeofs, and decltypes
3166 // - types which will become injected class names
3167 // Of course, we also need to rebuild any type referencing such a
3168 // type. It's safest to just say "dependent", but we call out a
3169 // few cases here.
3170
3171 DeclSpec &DS = D.getMutableDeclSpec();
3172 switch (DS.getTypeSpecType()) {
3173 case DeclSpec::TST_typename:
3174 case DeclSpec::TST_typeofType:
Sean Huntdb5d44b2011-05-19 05:37:45 +00003175 case DeclSpec::TST_decltype:
Eli Friedmanb001de72011-10-06 23:00:33 +00003176 case DeclSpec::TST_underlyingType:
3177 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00003178 // Grab the type from the parser.
3179 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00003180 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00003181 if (T.isNull() || !T->isDependentType()) break;
3182
3183 // Make sure there's a type source info. This isn't really much
3184 // of a waste; most dependent types should have type source info
3185 // attached already.
3186 if (!TSI)
3187 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3188
3189 // Rebuild the type in the current instantiation.
3190 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3191 if (!TSI) return true;
3192
3193 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00003194 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3195 DS.UpdateTypeRep(LocType);
3196 break;
3197 }
3198
3199 case DeclSpec::TST_typeofExpr: {
3200 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00003201 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00003202 if (Result.isInvalid()) return true;
3203 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00003204 break;
3205 }
3206
3207 default:
3208 // Nothing to do for these decl specs.
3209 break;
3210 }
3211
3212 // It doesn't matter what order we do this in.
3213 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3214 DeclaratorChunk &Chunk = D.getTypeObject(I);
3215
3216 // The only type information in the declarator which can come
3217 // before the declaration name is the base type of a member
3218 // pointer.
3219 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3220 continue;
3221
3222 // Rebuild the scope specifier in-place.
3223 CXXScopeSpec &SS = Chunk.Mem.Scope();
3224 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3225 return true;
3226 }
3227
3228 return false;
3229}
3230
Anders Carlsson3242ee02011-07-04 16:28:17 +00003231Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00003232 D.setFunctionDefinitionKind(FDK_Declaration);
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00003233 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3234
3235 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3236 Dcl->getDeclContext()->isFileContext())
3237 Dcl->setTopLevelDeclInObjCContainer();
3238
3239 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00003240}
3241
Richard Smith162e1c12011-04-15 14:24:37 +00003242/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3243/// If T is the name of a class, then each of the following shall have a
3244/// name different from T:
3245/// - every static data member of class T;
3246/// - every member function of class T
3247/// - every member of class T that is itself a type;
3248/// \returns true if the declaration name violates these rules.
3249bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3250 DeclarationNameInfo NameInfo) {
3251 DeclarationName Name = NameInfo.getName();
3252
3253 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3254 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3255 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3256 return true;
3257 }
3258
3259 return false;
3260}
Douglas Gregor42acead2012-03-17 23:06:31 +00003261
Douglas Gregor69605872012-03-28 16:01:27 +00003262/// \brief Diagnose a declaration whose declarator-id has the given
3263/// nested-name-specifier.
3264///
3265/// \param SS The nested-name-specifier of the declarator-id.
3266///
3267/// \param DC The declaration context to which the nested-name-specifier
3268/// resolves.
3269///
3270/// \param Name The name of the entity being declared.
3271///
3272/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00003273///
3274/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00003275bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00003276 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00003277 SourceLocation Loc) {
3278 DeclContext *Cur = CurContext;
3279 while (isa<LinkageSpecDecl>(Cur))
3280 Cur = Cur->getParent();
3281
3282 // C++ [dcl.meaning]p1:
3283 // A declarator-id shall not be qualified except for the definition
3284 // of a member function (9.3) or static data member (9.4) outside of
3285 // its class, the definition or explicit instantiation of a function
3286 // or variable member of a namespace outside of its namespace, or the
3287 // definition of an explicit specialization outside of its namespace,
3288 // or the declaration of a friend function that is a member of
3289 // another class or namespace (11.3). [...]
3290
3291 // The user provided a superfluous scope specifier that refers back to the
3292 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00003293 //
3294 // class X {
3295 // void X::f();
3296 // };
Douglas Gregor69605872012-03-28 16:01:27 +00003297 if (Cur->Equals(DC)) {
Douglas Gregor42acead2012-03-17 23:06:31 +00003298 Diag(Loc, diag::warn_member_extra_qualification)
3299 << Name << FixItHint::CreateRemoval(SS.getRange());
3300 SS.clear();
3301 return false;
3302 }
Douglas Gregor69605872012-03-28 16:01:27 +00003303
3304 // Check whether the qualifying scope encloses the scope of the original
3305 // declaration.
3306 if (!Cur->Encloses(DC)) {
3307 if (Cur->isRecord())
3308 Diag(Loc, diag::err_member_qualification)
3309 << Name << SS.getRange();
3310 else if (isa<TranslationUnitDecl>(DC))
3311 Diag(Loc, diag::err_invalid_declarator_global_scope)
3312 << Name << SS.getRange();
3313 else if (isa<FunctionDecl>(Cur))
3314 Diag(Loc, diag::err_invalid_declarator_in_function)
3315 << Name << SS.getRange();
3316 else
3317 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00003318 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00003319
Douglas Gregor42acead2012-03-17 23:06:31 +00003320 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00003321 }
3322
3323 if (Cur->isRecord()) {
3324 // Cannot qualify members within a class.
3325 Diag(Loc, diag::err_member_qualification)
3326 << Name << SS.getRange();
3327 SS.clear();
3328
3329 // C++ constructors and destructors with incorrect scopes can break
3330 // our AST invariants by having the wrong underlying types. If
3331 // that's the case, then drop this declaration entirely.
3332 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3333 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3334 !Context.hasSameType(Name.getCXXNameType(),
3335 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3336 return true;
3337
3338 return false;
3339 }
Douglas Gregor42acead2012-03-17 23:06:31 +00003340
Douglas Gregor69605872012-03-28 16:01:27 +00003341 // C++11 [dcl.meaning]p1:
3342 // [...] "The nested-name-specifier of the qualified declarator-id shall
3343 // not begin with a decltype-specifer"
3344 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3345 while (SpecLoc.getPrefix())
3346 SpecLoc = SpecLoc.getPrefix();
3347 if (dyn_cast_or_null<DecltypeType>(
3348 SpecLoc.getNestedNameSpecifier()->getAsType()))
3349 Diag(Loc, diag::err_decltype_in_declarator)
3350 << SpecLoc.getTypeLoc().getSourceRange();
3351
Douglas Gregor42acead2012-03-17 23:06:31 +00003352 return false;
3353}
3354
John McCalld226f652010-08-21 09:40:31 +00003355Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003356 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003357 // TODO: consider using NameInfo for diagnostic.
3358 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3359 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00003360
Chris Lattnere80a59c2007-07-25 00:24:17 +00003361 // All of these full declarators require an identifier. If it doesn't have
3362 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00003363 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00003364 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00003365 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003366 diag::err_declarator_need_ident)
3367 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00003368 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00003369 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3370 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Chris Lattner31e05722007-08-26 06:24:45 +00003372 // The scope passed in may not be a decl scope. Zip up the scope tree until
3373 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00003374 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003375 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00003376 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003377
John McCall63b43852010-04-29 23:50:39 +00003378 DeclContext *DC = CurContext;
3379 if (D.getCXXScopeSpec().isInvalid())
3380 D.setInvalidType();
3381 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00003382 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3383 UPPC_DeclarationQualifier))
3384 return 0;
3385
John McCall63b43852010-04-29 23:50:39 +00003386 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3387 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3388 if (!DC) {
3389 // If we could not compute the declaration context, it's because the
3390 // declaration context is dependent but does not refer to a class,
3391 // class template, or class template partial specialization. Complain
3392 // and return early, to avoid the coming semantic disaster.
3393 Diag(D.getIdentifierLoc(),
3394 diag::err_template_qualified_declarator_no_match)
3395 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3396 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00003397 return 0;
John McCall63b43852010-04-29 23:50:39 +00003398 }
John McCall63b43852010-04-29 23:50:39 +00003399 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00003400
John McCall63b43852010-04-29 23:50:39 +00003401 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00003402 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00003403 return 0;
John McCall63b43852010-04-29 23:50:39 +00003404
Douglas Gregor69605872012-03-28 16:01:27 +00003405 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3406 Diag(D.getIdentifierLoc(),
3407 diag::err_member_def_undefined_record)
3408 << Name << DC << D.getCXXScopeSpec().getRange();
3409 D.setInvalidType();
3410 } else if (!D.getDeclSpec().isFriendSpecified()) {
3411 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3412 Name, D.getIdentifierLoc())) {
3413 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00003414 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00003415
3416 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00003417 }
John McCall63b43852010-04-29 23:50:39 +00003418 }
3419
3420 // Check whether we need to rebuild the type of the given
3421 // declaration in the current instantiation.
3422 if (EnteringContext && IsDependentContext &&
3423 TemplateParamLists.size() != 0) {
3424 ContextRAII SavedContext(*this, DC);
3425 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3426 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00003427 }
3428 }
Richard Smith162e1c12011-04-15 14:24:37 +00003429
3430 if (DiagnoseClassNameShadow(DC, NameInfo))
3431 // If this is a typedef, we'll end up spewing multiple diagnostics.
3432 // Just return early; it's safer.
3433 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3434 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00003435
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003436 NamedDecl *New;
Douglas Gregorcda9c672009-02-16 17:45:42 +00003437
John McCallbf1a0282010-06-04 23:28:52 +00003438 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3439 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00003440
Douglas Gregord0937222010-12-13 22:49:22 +00003441 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3442 UPPC_DeclarationType))
3443 D.setInvalidType();
3444
Abramo Bagnara25777432010-08-11 22:01:17 +00003445 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00003446 ForRedeclaration);
3447
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003448 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00003449 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00003450 bool IsLinkageLookup = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00003451
3452 // If the declaration we're planning to build will be a function
3453 // or object with linkage, then look for another declaration with
3454 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3455 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3456 /* Do nothing*/;
3457 else if (R->isFunctionType()) {
Douglas Gregor6bec78d2009-07-07 17:00:05 +00003458 if (CurContext->isFunctionOrMethod() ||
3459 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00003460 IsLinkageLookup = true;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00003461 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall68263142009-11-18 22:49:29 +00003462 IsLinkageLookup = true;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003463 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor6bec78d2009-07-07 17:00:05 +00003464 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00003465 IsLinkageLookup = true;
3466
3467 if (IsLinkageLookup)
3468 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00003469
John McCall68263142009-11-18 22:49:29 +00003470 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003471 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00003472 LookupQualifiedName(Previous, DC);
3473
Douglas Gregor69605872012-03-28 16:01:27 +00003474 // C++ [dcl.meaning]p1:
3475 // When the declarator-id is qualified, the declaration shall refer to a
3476 // previously declared member of the class or namespace to which the
3477 // qualifier refers (or, in the case of a namespace, of an element of the
3478 // inline namespace set of that namespace (7.3.1)) or to a specialization
3479 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003480 //
Douglas Gregor69605872012-03-28 16:01:27 +00003481 // Note that we already checked the context above, and that we do not have
3482 // enough information to make sure that Previous contains the declaration
3483 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00003484 //
Douglas Gregor9d350972008-12-12 08:25:50 +00003485 // class X {
3486 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00003487 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00003488 // };
3489 //
Douglas Gregor584049d2008-12-15 23:53:10 +00003490 // void X::f(int) { } // ill-formed
3491 //
Douglas Gregor69605872012-03-28 16:01:27 +00003492 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00003493 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00003494 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00003495
3496 // C++ [dcl.meaning]p1:
3497 // [...] the member shall not merely have been introduced by a
3498 // using-declaration in the scope of the class or namespace nominated by
3499 // the nested-name-specifier of the declarator-id.
3500 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003501 }
3502
John McCall68263142009-11-18 22:49:29 +00003503 if (Previous.isSingleResult() &&
3504 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003505 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003506 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00003507 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3508 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregor72c3f312008-12-05 18:15:24 +00003510 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00003511 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00003512 }
3513
Douglas Gregor2ce52f32008-04-13 21:07:44 +00003514 // In C++, the previous declaration we find might be a tag type
3515 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00003516 // tag type. Note that this does does not apply if we're declaring a
3517 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00003518 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00003519 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00003520 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00003521
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003522 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00003523 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00003524 if (TemplateParamLists.size()) {
3525 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00003526 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00003527 }
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003529 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00003530 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003531 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00003532 move(TemplateParamLists),
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003533 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00003534 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003535 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3536 move(TemplateParamLists));
Reid Spencer5f016e22007-07-11 17:01:13 +00003537 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003538
3539 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00003540 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003542 // If this has an identifier and is not an invalid redeclaration or
3543 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003544 if (New->getDeclName() && AddToScope &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003545 !(D.isRedeclaration() && New->isInvalidDecl()))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003546 PushOnScopeChains(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00003547
John McCalld226f652010-08-21 09:40:31 +00003548 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00003549}
3550
Eli Friedman1ca48132009-02-21 00:44:51 +00003551/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3552/// types into constant array types in certain situations which would otherwise
3553/// be errors (for GCC compatibility).
3554static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3555 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00003556 bool &SizeIsNegative,
3557 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00003558 // This method tries to turn a variable array into a constant
3559 // array even when the size isn't an ICE. This is necessary
3560 // for compatibility with code that depends on gcc's buggy
3561 // constant expression folding, like struct {char x[(int)(char*)2];}
3562 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00003563 Oversized = 0;
3564
3565 if (T->isDependentType())
3566 return QualType();
3567
John McCall0953e762009-09-24 19:53:00 +00003568 QualifierCollector Qs;
3569 const Type *Ty = Qs.strip(T);
3570
3571 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00003572 QualType Pointee = PTy->getPointeeType();
3573 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00003574 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3575 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00003576 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00003577 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00003578 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00003579 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003580 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3581 QualType Inner = PTy->getInnerType();
3582 QualType FixedType =
3583 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3584 Oversized);
3585 if (FixedType.isNull()) return FixedType;
3586 FixedType = Context.getParenType(FixedType);
3587 return Qs.apply(Context, FixedType);
3588 }
Eli Friedman1ca48132009-02-21 00:44:51 +00003589
3590 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00003591 if (!VLATy)
3592 return QualType();
3593 // FIXME: We should probably handle this case
3594 if (VLATy->getElementType()->isVariablyModifiedType())
3595 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Richard Smithaa9c3502011-12-07 00:43:50 +00003597 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00003598 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00003599 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00003600 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00003601
Douglas Gregor2767ce22010-08-18 00:39:00 +00003602 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00003603 if (Res.isSigned() && Res.isNegative()) {
3604 SizeIsNegative = true;
3605 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003606 }
Eli Friedman1ca48132009-02-21 00:44:51 +00003607
Douglas Gregor2767ce22010-08-18 00:39:00 +00003608 // Check whether the array is too large to be addressed.
3609 unsigned ActiveSizeBits
3610 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3611 Res);
3612 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3613 Oversized = Res;
3614 return QualType();
3615 }
3616
3617 return Context.getConstantArrayType(VLATy->getElementType(),
3618 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00003619}
3620
Douglas Gregor63935192009-03-02 00:19:53 +00003621/// \brief Register the given locally-scoped external C declaration so
3622/// that it can be found later for redeclarations
Mike Stump1eb44332009-09-09 15:08:12 +00003623void
John McCall68263142009-11-18 22:49:29 +00003624Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3625 const LookupResult &Previous,
Douglas Gregor63935192009-03-02 00:19:53 +00003626 Scope *S) {
3627 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3628 "Decl is not a locally-scoped decl!");
3629 // Note that we have a locally-scoped external with this name.
3630 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3631
John McCall68263142009-11-18 22:49:29 +00003632 if (!Previous.isSingleResult())
Douglas Gregor63935192009-03-02 00:19:53 +00003633 return;
3634
John McCall68263142009-11-18 22:49:29 +00003635 NamedDecl *PrevDecl = Previous.getFoundDecl();
3636
Douglas Gregor63935192009-03-02 00:19:53 +00003637 // If there was a previous declaration of this variable, it may be
3638 // in our identifier chain. Update the identifier chain with the new
3639 // declaration.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003640 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor63935192009-03-02 00:19:53 +00003641 // The previous declaration was found on the identifer resolver
3642 // chain, so remove it from its scope.
Douglas Gregore12a11f2011-06-29 21:22:02 +00003643
3644 if (S->isDeclScope(PrevDecl)) {
3645 // Special case for redeclarations in the SAME scope.
3646 // Because this declaration is going to be added to the identifier chain
3647 // later, we should temporarily take it OFF the chain.
3648 IdResolver.RemoveDecl(ND);
3649
3650 } else {
3651 // Find the scope for the original declaration.
3652 while (S && !S->isDeclScope(PrevDecl))
3653 S = S->getParent();
3654 }
Douglas Gregor63935192009-03-02 00:19:53 +00003655
3656 if (S)
John McCalld226f652010-08-21 09:40:31 +00003657 S->RemoveDecl(PrevDecl);
Douglas Gregor63935192009-03-02 00:19:53 +00003658 }
3659}
3660
Douglas Gregorec12ce22011-07-28 14:20:37 +00003661llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3662Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3663 if (ExternalSource) {
3664 // Load locally-scoped external decls from the external source.
3665 SmallVector<NamedDecl *, 4> Decls;
3666 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3667 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3668 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3669 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3670 if (Pos == LocallyScopedExternalDecls.end())
3671 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3672 }
3673 }
3674
3675 return LocallyScopedExternalDecls.find(Name);
3676}
3677
Eli Friedman85a53192009-04-07 19:37:57 +00003678/// \brief Diagnose function specifiers on a declaration of an identifier that
3679/// does not identify a function.
3680void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3681 // FIXME: We should probably indicate the identifier in question to avoid
3682 // confusion for constructs like "inline int a(), b;"
3683 if (D.getDeclSpec().isInlineSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00003684 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00003685 diag::err_inline_non_function);
3686
3687 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00003688 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00003689 diag::err_virtual_non_function);
3690
3691 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00003692 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00003693 diag::err_explicit_non_function);
3694}
3695
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003696NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003697Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003698 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003699 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3700 if (D.getCXXScopeSpec().isSet()) {
3701 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3702 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003703 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003704 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00003705 DC = CurContext;
3706 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003707 }
3708
David Blaikie4e4d0842012-03-11 07:00:24 +00003709 if (getLangOpts().CPlusPlus) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003710 // Check that there are no default arguments (C++ only).
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003711 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003712 }
3713
Eli Friedman85a53192009-04-07 19:37:57 +00003714 DiagnoseFunctionSpecifiers(D);
3715
Eli Friedman63054b32009-04-19 20:27:55 +00003716 if (D.getDeclSpec().isThreadSpecified())
3717 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003718 if (D.getDeclSpec().isConstexprSpecified())
3719 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3720 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00003721
Douglas Gregoraef01992010-07-13 06:37:01 +00003722 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3723 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3724 << D.getName().getSourceRange();
3725 return 0;
3726 }
3727
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003728 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003729 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003731 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003732 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00003733
Richard Smith3e4c6c42011-05-05 21:57:07 +00003734 CheckTypedefForVariablyModifiedType(S, NewTD);
3735
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003736 bool Redeclaration = D.isRedeclaration();
3737 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3738 D.setRedeclaration(Redeclaration);
3739 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00003740}
3741
Richard Smith3e4c6c42011-05-05 21:57:07 +00003742void
3743Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00003744 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3745 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00003746 // Note that variably modified types must be fixed before merging the decl so
3747 // that redeclarations will match.
Chris Lattner38c5ebd2009-04-19 05:21:20 +00003748 QualType T = NewTD->getUnderlyingType();
3749 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00003750 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Chris Lattner38c5ebd2009-04-19 05:21:20 +00003752 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00003753 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00003754 llvm::APSInt Oversized;
Eli Friedman1ca48132009-02-21 00:44:51 +00003755 QualType FixedTy =
Douglas Gregor2767ce22010-08-18 00:39:00 +00003756 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3757 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00003758 if (!FixedTy.isNull()) {
Richard Smith162e1c12011-04-15 14:24:37 +00003759 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCalla93c9342009-12-07 02:54:59 +00003760 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedman1ca48132009-02-21 00:44:51 +00003761 } else {
3762 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00003763 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00003764 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00003765 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00003766 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00003767 Diag(NewTD->getLocation(), diag::err_array_too_large)
3768 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00003769 else
Richard Smith162e1c12011-04-15 14:24:37 +00003770 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003771 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00003772 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003773 }
3774 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00003775}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003776
Richard Smith3e4c6c42011-05-05 21:57:07 +00003777
3778/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3779/// declares a typedef-name, either using the 'typedef' type specifier or via
3780/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3781NamedDecl*
3782Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3783 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00003784 // Merge the decl with the existing one if appropriate. If the decl is
3785 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003786 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00003787 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00003788 if (!Previous.empty()) {
3789 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00003790 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00003791 }
3792
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003793 // If this is the C FILE type, notify the AST context.
3794 if (IdentifierInfo *II = NewTD->getIdentifier())
3795 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003796 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00003797 if (II->isStr("FILE"))
3798 Context.setFILEDecl(NewTD);
3799 else if (II->isStr("jmp_buf"))
3800 Context.setjmp_bufDecl(NewTD);
3801 else if (II->isStr("sigjmp_buf"))
3802 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00003803 else if (II->isStr("ucontext_t"))
3804 Context.setucontext_tDecl(NewTD);
Douglas Gregor4a1bb8c2010-10-05 15:41:24 +00003805 else if (II->isStr("__builtin_va_list"))
3806 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stump782fa302009-07-28 02:25:19 +00003807 }
3808
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00003809 return NewTD;
3810}
3811
Douglas Gregor8f301052009-02-24 19:23:27 +00003812/// \brief Determines whether the given declaration is an out-of-scope
3813/// previous declaration.
3814///
3815/// This routine should be invoked when name lookup has found a
3816/// previous declaration (PrevDecl) that is not in the scope where a
3817/// new declaration by the same name is being introduced. If the new
3818/// declaration occurs in a local scope, previous declarations with
3819/// linkage may still be considered previous declarations (C99
3820/// 6.2.2p4-5, C++ [basic.link]p6).
3821///
3822/// \param PrevDecl the previous declaration found by name
3823/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00003824///
Douglas Gregor8f301052009-02-24 19:23:27 +00003825/// \param DC the context in which the new declaration is being
3826/// declared.
3827///
3828/// \returns true if PrevDecl is an out-of-scope previous declaration
3829/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00003830static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00003831isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3832 ASTContext &Context) {
3833 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00003834 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00003835
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00003836 if (!PrevDecl->hasLinkage())
3837 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00003838
David Blaikie4e4d0842012-03-11 07:00:24 +00003839 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00003840 // C++ [basic.link]p6:
3841 // If there is a visible declaration of an entity with linkage
3842 // having the same name and type, ignoring entities declared
3843 // outside the innermost enclosing namespace scope, the block
3844 // scope declaration declares that same entity and receives the
3845 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003846 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00003847 if (!OuterContext->isFunctionOrMethod())
3848 // This rule only applies to block-scope declarations.
3849 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00003850
3851 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3852 if (PrevOuterContext->isRecord())
3853 // We found a member function: ignore it.
3854 return false;
3855
3856 // Find the innermost enclosing namespace for the new and
3857 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003858 OuterContext = OuterContext->getEnclosingNamespaceContext();
3859 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Douglas Gregor757c6002010-08-27 22:55:10 +00003861 // The previous declaration is in a different namespace, so it
3862 // isn't the same function.
3863 if (!OuterContext->Equals(PrevOuterContext))
3864 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00003865 }
3866
Douglas Gregor8f301052009-02-24 19:23:27 +00003867 return true;
3868}
3869
John McCallb6217662010-03-15 10:12:16 +00003870static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3871 CXXScopeSpec &SS = D.getCXXScopeSpec();
3872 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00003873 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00003874}
3875
John McCallf85e1932011-06-15 23:02:42 +00003876bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3877 QualType type = decl->getType();
3878 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3879 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3880 // Various kinds of declaration aren't allowed to be __autoreleasing.
3881 unsigned kind = -1U;
3882 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3883 if (var->hasAttr<BlocksAttr>())
3884 kind = 0; // __block
3885 else if (!var->hasLocalStorage())
3886 kind = 1; // global
3887 } else if (isa<ObjCIvarDecl>(decl)) {
3888 kind = 3; // ivar
3889 } else if (isa<FieldDecl>(decl)) {
3890 kind = 2; // field
3891 }
3892
3893 if (kind != -1U) {
3894 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3895 << kind;
3896 }
3897 } else if (lifetime == Qualifiers::OCL_None) {
3898 // Try to infer lifetime.
3899 if (!type->isObjCLifetimeType())
3900 return false;
3901
3902 lifetime = type->getObjCARCImplicitLifetime();
3903 type = Context.getLifetimeQualifiedType(type, lifetime);
3904 decl->setType(type);
3905 }
3906
3907 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3908 // Thread-local variables cannot have lifetime.
3909 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3910 var->isThreadSpecified()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003911 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00003912 << var->getType();
3913 return true;
3914 }
3915 }
3916
3917 return false;
3918}
3919
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003920NamedDecl*
Chris Lattner16c5dea2010-10-10 18:16:20 +00003921Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00003922 TypeSourceInfo *TInfo, LookupResult &Previous,
3923 MultiTemplateParamsArg TemplateParamLists) {
3924 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00003925 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003926
3927 // Check that there are no default arguments (C++ only).
David Blaikie4e4d0842012-03-11 07:00:24 +00003928 if (getLangOpts().CPlusPlus)
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003929 CheckExtraCXXDefaultArguments(D);
3930
Douglas Gregor16573fa2010-04-19 22:54:31 +00003931 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3932 assert(SCSpec != DeclSpec::SCS_typedef &&
3933 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnara35f9a192010-07-30 16:47:02 +00003934 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003935 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003936 // mutable can only appear on non-static class members, so it's always
3937 // an error here
3938 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003939 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003940 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003941 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00003942 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3943 VarDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00003944 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003945
3946 IdentifierInfo *II = Name.getAsIdentifierInfo();
3947 if (!II) {
3948 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00003949 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003950 return 0;
3951 }
3952
Eli Friedman85a53192009-04-07 19:37:57 +00003953 DiagnoseFunctionSpecifiers(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003954
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00003955 if (!DC->isRecord() && S->getFnParent() == 0) {
3956 // C99 6.9p2: The storage-class specifiers auto and register shall not
3957 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00003958 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump1eb44332009-09-09 15:08:12 +00003959
Chris Lattnerd4b19d52009-05-12 21:44:00 +00003960 // If this is a register variable with an asm label specified, then this
3961 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00003962 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00003963 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3964 else
3965 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003966 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003967 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003968 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003969
David Blaikie4e4d0842012-03-11 07:00:24 +00003970 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00003971 // Set up the special work-group-local storage class for variables in the
3972 // OpenCL __local address space.
3973 if (R.getAddressSpace() == LangAS::opencl_local)
3974 SC = SC_OpenCLWorkGroupLocal;
3975 }
3976
Ted Kremenek9577abc2011-01-23 17:04:59 +00003977 bool isExplicitSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003978 VarDecl *NewVD;
David Blaikie4e4d0842012-03-11 07:00:24 +00003979 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003980 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003981 D.getIdentifierLoc(), II,
3982 R, TInfo, SC, SCAsWritten);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003983
3984 if (D.isInvalidType())
3985 NewVD->setInvalidDecl();
3986 } else {
3987 if (DC->isRecord() && !CurContext->isRecord()) {
3988 // This is an out-of-line definition of a static data member.
3989 if (SC == SC_Static) {
3990 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3991 diag::err_static_out_of_line)
3992 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3993 } else if (SC == SC_None)
3994 SC = SC_Static;
Anders Carlssone98da2e2009-06-24 00:28:53 +00003995 }
Richard Smithb9c64d82012-02-16 20:41:22 +00003996 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003997 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3998 if (RD->isLocalClass())
3999 Diag(D.getIdentifierLoc(),
4000 diag::err_static_data_member_not_allowed_in_local_class)
4001 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004002
Richard Smithb9c64d82012-02-16 20:41:22 +00004003 // C++98 [class.union]p1: If a union contains a static data member,
4004 // the program is ill-formed. C++11 drops this restriction.
4005 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004006 Diag(D.getIdentifierLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004007 getLangOpts().CPlusPlus0x
Richard Smithb9c64d82012-02-16 20:41:22 +00004008 ? diag::warn_cxx98_compat_static_data_member_in_union
4009 : diag::ext_static_data_member_in_union) << Name;
4010 // We conservatively disallow static data members in anonymous structs.
4011 else if (!RD->getDeclName())
4012 Diag(D.getIdentifierLoc(),
4013 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004014 << Name << RD->isUnion();
4015 }
4016 }
4017
4018 // Match up the template parameter lists with the scope specifier, then
4019 // determine whether we have a template or a template specialization.
4020 isExplicitSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004021 bool Invalid = false;
4022 if (TemplateParameterList *TemplateParams
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004023 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar96a00142012-03-09 18:35:03 +00004024 D.getDeclSpec().getLocStart(),
Douglas Gregorc8406492011-05-10 18:27:06 +00004025 D.getIdentifierLoc(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004026 D.getCXXScopeSpec(),
John McCall9a34edb2010-10-19 01:40:49 +00004027 TemplateParamLists.get(),
4028 TemplateParamLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004029 /*never a friend*/ false,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004030 isExplicitSpecialization,
4031 Invalid)) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004032 if (TemplateParams->size() > 0) {
4033 // There is no such thing as a variable template.
4034 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4035 << II
4036 << SourceRange(TemplateParams->getTemplateLoc(),
4037 TemplateParams->getRAngleLoc());
4038 return 0;
4039 } else {
4040 // There is an extraneous 'template<>' for this variable. Complain
4041 // about it, but allow the declaration of the variable.
4042 Diag(TemplateParams->getTemplateLoc(),
4043 diag::err_template_variable_noparams)
4044 << II
4045 << SourceRange(TemplateParams->getTemplateLoc(),
4046 TemplateParams->getRAngleLoc());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004047 }
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00004048 }
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Daniel Dunbar96a00142012-03-09 18:35:03 +00004050 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004051 D.getIdentifierLoc(), II,
4052 R, TInfo, SC, SCAsWritten);
Eli Friedman63054b32009-04-19 20:27:55 +00004053
Richard Smith483b9f32011-02-21 20:05:19 +00004054 // If this decl has an auto type in need of deduction, make a note of the
4055 // Decl so we can diagnose uses of it in its own initializer.
4056 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4057 R->getContainedAutoType())
4058 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00004059
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004060 if (D.isInvalidType() || Invalid)
4061 NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004062
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004063 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00004064
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004065 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004066 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004067 TemplateParamLists.size(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004068 TemplateParamLists.release());
4069 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004070
Richard Smith7ca48502012-02-13 22:16:19 +00004071 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00004072 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00004073 }
4074
Douglas Gregore3895852011-09-12 18:37:38 +00004075 // Set the lexical context. If the declarator has a C++ scope specifier, the
4076 // lexical context will be different from the semantic context.
4077 NewVD->setLexicalDeclContext(CurContext);
4078
Eli Friedman63054b32009-04-19 20:27:55 +00004079 if (D.getDeclSpec().isThreadSpecified()) {
4080 if (NewVD->hasLocalStorage())
4081 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004082 else if (!Context.getTargetInfo().isTLSSupported())
Eli Friedman4fb71b02009-04-19 21:48:33 +00004083 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00004084 else
4085 NewVD->setThreadSpecified(true);
4086 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004087
Douglas Gregord023aec2011-09-09 20:53:38 +00004088 if (D.getDeclSpec().isModulePrivateSpecified()) {
4089 if (isExplicitSpecialization)
4090 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4091 << 2
4092 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00004093 else if (NewVD->hasLocalStorage())
4094 Diag(NewVD->getLocation(), diag::err_module_private_local)
4095 << 0 << NewVD->getDeclName()
4096 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4097 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregord023aec2011-09-09 20:53:38 +00004098 else
4099 NewVD->setModulePrivate();
4100 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00004101
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004102 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004103 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004104
John McCallf85e1932011-06-15 23:02:42 +00004105 // In auto-retain/release, infer strong retension for variables of
4106 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00004107 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00004108 NewVD->setInvalidDecl();
4109
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004110 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00004111 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004112 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00004113 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004114 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00004115 if (S->getFnParent() != 0) {
4116 switch (SC) {
4117 case SC_None:
4118 case SC_Auto:
4119 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4120 break;
4121 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004122 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00004123 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4124 break;
4125 case SC_Static:
4126 case SC_Extern:
4127 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004128 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00004129 break;
4130 }
4131 }
4132
4133 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00004134 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00004135 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4136 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4137 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4138 if (I != ExtnameUndeclaredIdentifiers.end()) {
4139 NewVD->addAttr(I->second);
4140 ExtnameUndeclaredIdentifiers.erase(I);
4141 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004142 }
4143
John McCall8472af42010-03-16 21:48:18 +00004144 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00004145 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00004146 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00004147
John McCall68263142009-11-18 22:49:29 +00004148 // Don't consider existing declarations that are in a different
4149 // scope and are out-of-semantic-context declarations (if the new
4150 // declaration has linkage).
Richard Smith3e4c6c42011-05-05 21:57:07 +00004151 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregorcc209452011-03-07 16:54:27 +00004152 isExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004153
David Blaikie4e4d0842012-03-11 07:00:24 +00004154 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004155 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4156 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004157 // Merge the decl with the existing one if appropriate.
4158 if (!Previous.empty()) {
4159 if (Previous.isSingleResult() &&
4160 isa<FieldDecl>(Previous.getFoundDecl()) &&
4161 D.getCXXScopeSpec().isSet()) {
4162 // The user tried to define a non-static data member
4163 // out-of-line (C++ [dcl.meaning]p1).
4164 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4165 << D.getCXXScopeSpec().getRange();
4166 Previous.clear();
4167 NewVD->setInvalidDecl();
4168 }
4169 } else if (D.getCXXScopeSpec().isSet()) {
4170 // No previous declaration in the qualifying scope.
4171 Diag(D.getIdentifierLoc(), diag::err_no_member)
4172 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004173 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004174 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004175 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004176
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004177 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004178
4179 // This is an explicit specialization of a static data member. Check it.
4180 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4181 CheckMemberSpecialization(NewVD, Previous))
4182 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004183 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004184
Ryan Flynn478fbc62009-07-25 22:29:44 +00004185 // attributes declared post-definition are currently ignored
Sean Huntcf807c42010-08-18 23:23:40 +00004186 // FIXME: This should be handled in attribute merging, not
4187 // here.
John McCall68263142009-11-18 22:49:29 +00004188 if (Previous.isSingleResult()) {
Sebastian Redl31310a22010-02-01 20:16:42 +00004189 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4190 if (Def && (Def = Def->getDefinition()) &&
4191 Def != NewVD && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00004192 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4193 Diag(Def->getLocation(), diag::note_previous_definition);
4194 }
4195 }
4196
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004197 // If this is a locally-scoped extern C variable, update the map of
4198 // such variables.
Douglas Gregor48a83b52009-09-12 00:17:51 +00004199 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnereaaebc72009-04-25 08:06:05 +00004200 !NewVD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00004201 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004202
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004203 // If there's a #pragma GCC visibility in scope, and this isn't a class
4204 // member, set the visibility of this variable.
4205 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4206 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004207
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004208 MarkUnusedFileScopedDecl(NewVD);
4209
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004210 return NewVD;
4211}
4212
John McCall053f4bd2010-03-22 09:20:08 +00004213/// \brief Diagnose variable or built-in function shadowing. Implements
4214/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00004215///
John McCall053f4bd2010-03-22 09:20:08 +00004216/// This method is called whenever a VarDecl is added to a "useful"
4217/// scope.
John McCall8472af42010-03-16 21:48:18 +00004218///
John McCalla369a952010-03-20 04:12:52 +00004219/// \param S the scope in which the shadowing name is being declared
4220/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00004221///
John McCall053f4bd2010-03-22 09:20:08 +00004222void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00004223 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004224 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00004225 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00004226 return;
4227
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00004228 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00004229 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00004230 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00004231
4232 DeclContext *NewDC = D->getDeclContext();
4233
John McCalla369a952010-03-20 04:12:52 +00004234 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00004235 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00004236 return;
John McCall8472af42010-03-16 21:48:18 +00004237
John McCall8472af42010-03-16 21:48:18 +00004238 NamedDecl* ShadowedDecl = R.getFoundDecl();
4239 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4240 return;
4241
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00004242 // Fields are not shadowed by variables in C++ static methods.
4243 if (isa<FieldDecl>(ShadowedDecl))
4244 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4245 if (MD->isStatic())
4246 return;
4247
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00004248 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4249 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00004250 // For shadowing external vars, make sure that we point to the global
4251 // declaration, not a locally scoped extern declaration.
4252 for (VarDecl::redecl_iterator
4253 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4254 I != E; ++I)
4255 if (I->isFileVarDecl()) {
4256 ShadowedDecl = *I;
4257 break;
4258 }
4259 }
4260
4261 DeclContext *OldDC = ShadowedDecl->getDeclContext();
4262
John McCalla369a952010-03-20 04:12:52 +00004263 // Only warn about certain kinds of shadowing for class members.
4264 if (NewDC && NewDC->isRecord()) {
4265 // In particular, don't warn about shadowing non-class members.
4266 if (!OldDC->isRecord())
4267 return;
4268
4269 // TODO: should we warn about static data members shadowing
4270 // static data members from base classes?
4271
4272 // TODO: don't diagnose for inaccessible shadowed members.
4273 // This is hard to do perfectly because we might friend the
4274 // shadowing context, but that's just a false negative.
4275 }
4276
4277 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00004278 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00004279 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00004280 if (isa<FieldDecl>(ShadowedDecl))
4281 Kind = 3; // field
4282 else
4283 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00004284 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00004285 Kind = 1; // global
4286 else
4287 Kind = 0; // local
4288
John McCalla369a952010-03-20 04:12:52 +00004289 DeclarationName Name = R.getLookupName();
4290
John McCall8472af42010-03-16 21:48:18 +00004291 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00004292 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00004293 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4294}
4295
John McCall053f4bd2010-03-22 09:20:08 +00004296/// \brief Check -Wshadow without the advantage of a previous lookup.
4297void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004298 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00004299 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004300 return;
4301
John McCall053f4bd2010-03-22 09:20:08 +00004302 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4303 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4304 LookupName(R, S);
4305 CheckShadow(S, D, R);
4306}
4307
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004308/// \brief Perform semantic checking on a newly-created variable
4309/// declaration.
4310///
4311/// This routine performs all of the type-checking required for a
Douglas Gregor180bb632009-05-01 15:47:09 +00004312/// variable declaration once it has been built. It is used both to
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004313/// check variables after they have been parsed and their declarators
Douglas Gregor180bb632009-05-01 15:47:09 +00004314/// have been translated into a declaration, and to check variables
4315/// that have been instantiated from a template.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004316///
Chris Lattnereaaebc72009-04-25 08:06:05 +00004317/// Sets NewVD->isInvalidDecl() if an error was encountered.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004318///
4319/// Returns true if the variable declaration is a redeclaration.
4320bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4321 LookupResult &Previous) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004322 // If the decl is already known invalid, don't check it.
4323 if (NewVD->isInvalidDecl())
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004324 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004325
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004326 QualType T = NewVD->getType();
4327
John McCallc12c5bb2010-05-15 11:32:37 +00004328 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00004329 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4330 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00004331 T = Context.getObjCObjectPointerType(T);
4332 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004333 }
Mike Stump1eb44332009-09-09 15:08:12 +00004334
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004335 // Emit an error if an address space was applied to decl with local storage.
4336 // This includes arrays of objects with address space qualifiers, but not
4337 // automatic variables that point to other address spaces.
4338 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00004339 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004340 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004341 NewVD->setInvalidDecl();
4342 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004343 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00004344
Mike Stumpf33651c2009-04-14 00:57:29 +00004345 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00004346 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004347 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00004348 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4349 else
4350 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4351 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00004352
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004353 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00004354 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00004355 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00004356 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004358 if ((isVM && NewVD->hasLinkage()) ||
4359 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004360 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004361 llvm::APSInt Oversized;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004362 QualType FixedTy =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004363 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4364 Oversized);
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Chris Lattnereaaebc72009-04-25 08:06:05 +00004366 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004367 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004368 // FIXME: This won't give the correct result for
4369 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004370 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004372 if (NewVD->isFileVarDecl())
4373 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00004374 << SizeRange;
John McCalld931b082010-08-26 03:08:43 +00004375 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004376 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00004377 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004378 else
4379 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00004380 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004381 NewVD->setInvalidDecl();
4382 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004383 }
4384
Chris Lattnereaaebc72009-04-25 08:06:05 +00004385 if (FixedTy.isNull()) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004386 if (NewVD->isFileVarDecl())
4387 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4388 else
4389 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004390 NewVD->setInvalidDecl();
4391 return false;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004392 }
Mike Stump1eb44332009-09-09 15:08:12 +00004393
Chris Lattnereaaebc72009-04-25 08:06:05 +00004394 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4395 NewVD->setType(FixedTy);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00004396 }
4397
John McCall68263142009-11-18 22:49:29 +00004398 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00004399 // Since we did not find anything by this name and we're declaring
4400 // an extern "C" variable, look for a non-visible extern "C"
4401 // declaration with the same name.
4402 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorec12ce22011-07-28 14:20:37 +00004403 = findLocallyScopedExternalDecl(NewVD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00004404 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00004405 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00004406 }
4407
Chris Lattnereaaebc72009-04-25 08:06:05 +00004408 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004409 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4410 << T;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004411 NewVD->setInvalidDecl();
4412 return false;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004413 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004414
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004415 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00004416 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004417 NewVD->setInvalidDecl();
4418 return false;
Mike Stumpea000bf2009-04-30 00:19:40 +00004419 }
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004421 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpc975bb02009-05-01 23:41:47 +00004422 Diag(NewVD->getLocation(), diag::err_block_on_vm);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004423 NewVD->setInvalidDecl();
4424 return false;
Mike Stumpc975bb02009-05-01 23:41:47 +00004425 }
4426
Richard Smith7ca48502012-02-13 22:16:19 +00004427 if (NewVD->isConstexpr() && !T->isDependentType() &&
4428 RequireLiteralType(NewVD->getLocation(), T,
4429 PDiag(diag::err_constexpr_var_non_literal))) {
4430 NewVD->setInvalidDecl();
4431 return false;
4432 }
4433
John McCall68263142009-11-18 22:49:29 +00004434 if (!Previous.empty()) {
John McCall68263142009-11-18 22:49:29 +00004435 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004436 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004437 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004438 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004439}
4440
Douglas Gregora8f32e02009-10-06 17:59:45 +00004441/// \brief Data used with FindOverriddenMethod
4442struct FindOverriddenMethodData {
4443 Sema *S;
4444 CXXMethodDecl *Method;
4445};
4446
4447/// \brief Member lookup function that determines whether a given C++
4448/// method overrides a method in a base class, to be used with
4449/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00004450static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00004451 CXXBasePath &Path,
4452 void *UserData) {
4453 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00004454
Douglas Gregora8f32e02009-10-06 17:59:45 +00004455 FindOverriddenMethodData *Data
4456 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00004457
4458 DeclarationName Name = Data->Method->getDeclName();
4459
4460 // FIXME: Do we care about other names here too?
4461 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00004462 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00004463 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4464 CanQualType CT = Data->S->Context.getCanonicalType(T);
4465
Anders Carlsson1a689722009-11-27 01:26:58 +00004466 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00004467 }
4468
4469 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregora8f32e02009-10-06 17:59:45 +00004470 Path.Decls.first != Path.Decls.second;
4471 ++Path.Decls.first) {
John McCall52a02752010-06-16 09:33:39 +00004472 NamedDecl *D = *Path.Decls.first;
John McCallad00b772010-06-16 08:42:20 +00004473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4474 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00004475 return true;
4476 }
4477 }
4478
4479 return false;
4480}
4481
Douglas Gregor74e2fc32012-04-16 18:27:27 +00004482static bool hasDelayedExceptionSpec(CXXMethodDecl *Method) {
4483 const FunctionProtoType *Proto =Method->getType()->getAs<FunctionProtoType>();
4484 return Proto && Proto->getExceptionSpecType() == EST_Delayed;
4485}
4486
Sebastian Redla165da02009-11-18 21:51:29 +00004487/// AddOverriddenMethods - See if a method overrides any in the base classes,
4488/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00004489bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00004490 // Look for virtual methods in base classes that this method might override.
4491 CXXBasePaths Paths;
4492 FindOverriddenMethodData Data;
4493 Data.Method = MD;
4494 Data.S = this;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00004495 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00004496 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4497 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4498 E = Paths.found_decls_end(); I != E; ++I) {
4499 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00004500 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00004501 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Douglas Gregor74e2fc32012-04-16 18:27:27 +00004502 (hasDelayedExceptionSpec(MD) ||
4503 !CheckOverridingFunctionExceptionSpec(MD, OldMD)) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00004504 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00004505 AddedAny = true;
4506 }
Sebastian Redla165da02009-11-18 21:51:29 +00004507 }
4508 }
4509 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00004510
4511 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00004512}
4513
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004514namespace {
4515 // Struct for holding all of the extra arguments needed by
4516 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4517 struct ActOnFDArgs {
4518 Scope *S;
4519 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004520 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004521 bool AddToScope;
4522 };
4523}
4524
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00004525namespace {
4526
4527// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00004528// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00004529class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4530 public:
Kaelyn Uhrain33363532012-02-16 22:40:59 +00004531 DifferentNameValidatorCCC(CXXRecordDecl *Parent)
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004532 : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00004533
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00004534 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00004535 if (candidate.getEditDistance() == 0)
4536 return false;
4537
4538 if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) {
4539 CXXRecordDecl *Parent = MD->getParent();
4540 return Parent && Parent->getCanonicalDecl() == ExpectedParent;
4541 }
4542
4543 return !ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00004544 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00004545
4546 private:
4547 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00004548};
4549
4550}
4551
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004552/// \brief Generate diagnostics for an invalid function redeclaration.
4553///
4554/// This routine handles generating the diagnostic messages for an invalid
4555/// function redeclaration, including finding possible similar declarations
4556/// or performing typo correction if there are no previous declarations with
4557/// the same name.
4558///
4559/// Returns a NamedDecl iff typo correction was performed and substituting in
4560/// the new declaration name does not cause new errors.
4561static NamedDecl* DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004562 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004563 ActOnFDArgs &ExtraArgs) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004564 NamedDecl *Result = NULL;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004565 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004566 DeclContext *NewDC = NewFD->getDeclContext();
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004567 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
John McCall29ae6e52010-10-13 05:45:15 +00004568 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00004569 llvm::SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004570 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4571 TypoCorrection Correction;
David Blaikie4e4d0842012-03-11 07:00:24 +00004572 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004573 ExtraArgs.D.getDeclSpec().isFriendSpecified());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004574 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4575 : diag::err_member_def_does_not_match;
4576
4577 NewFD->setInvalidDecl();
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004578 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00004579 assert(!Prev.isAmbiguous() &&
4580 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00004581 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4582 DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004583 if (!Prev.empty()) {
4584 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4585 Func != FuncEnd; ++Func) {
4586 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004587 if (FD &&
4588 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004589 // Add 1 to the index so that 0 can mean the mismatch didn't
4590 // involve a parameter
4591 unsigned ParamNum =
4592 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4593 NearMatches.push_back(std::make_pair(FD, ParamNum));
4594 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00004595 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004596 // If the qualified name lookup yielded nothing, try typo correction
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004597 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00004598 Prev.getLookupKind(), 0, 0,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004599 Validator, NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004600 // Trap errors.
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004601 Sema::SFINAETrap Trap(SemaRef);
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004602
4603 // Set up everything for the call to ActOnFunctionDeclarator
4604 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4605 ExtraArgs.D.getIdentifierLoc());
4606 Previous.clear();
4607 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004608 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4609 CDeclEnd = Correction.end();
4610 CDecl != CDeclEnd; ++CDecl) {
4611 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004612 if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4613 MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004614 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004615 }
4616 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004617 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004618 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4619 // pieces need to verify the typo-corrected C++ declaraction and hopefully
4620 // eliminate the need for the parameter pack ExtraArgs.
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004621 Result = SemaRef.ActOnFunctionDeclarator(
4622 ExtraArgs.S, ExtraArgs.D,
4623 Correction.getCorrectionDecl()->getDeclContext(),
4624 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4625 ExtraArgs.AddToScope);
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004626 if (Trap.hasErrorOccurred()) {
4627 // Pretend the typo correction never occurred
4628 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4629 ExtraArgs.D.getIdentifierLoc());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004630 ExtraArgs.D.setRedeclaration(wasRedeclaration);
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004631 Previous.clear();
4632 Previous.setLookupName(Name);
4633 Result = NULL;
4634 } else {
4635 for (LookupResult::iterator Func = Previous.begin(),
4636 FuncEnd = Previous.end();
4637 Func != FuncEnd; ++Func) {
4638 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4639 NearMatches.push_back(std::make_pair(FD, 0));
4640 }
4641 }
4642 if (NearMatches.empty()) {
4643 // Ignore the correction if it didn't yield any close FunctionDecl matches
4644 Correction = TypoCorrection();
4645 } else {
Kaelyn Uhrain7c243342011-09-14 19:37:32 +00004646 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4647 : diag::err_member_def_does_not_match_suggest;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004648 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004649 }
4650
4651 if (Correction)
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004652 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00004653 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004654 << FixItHint::CreateReplacement(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004655 NewFD->getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004656 Correction.getAsString(SemaRef.getLangOpts()));
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004657 else
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004658 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4659 << Name << NewDC << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004660
Kaelyn Uhrain10553932011-10-10 18:01:37 +00004661 bool NewFDisConst = false;
4662 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4663 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4664
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004665 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4666 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4667 NearMatch != NearMatchEnd; ++NearMatch) {
4668 FunctionDecl *FD = NearMatch->first;
Kaelyn Uhrain10553932011-10-10 18:01:37 +00004669 bool FDisConst = false;
4670 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4671 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004672
4673 if (unsigned Idx = NearMatch->second) {
4674 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00004675 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
4676 if (Loc.isInvalid()) Loc = FD->getLocation();
4677 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004678 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4679 } else if (Correction) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004680 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
David Blaikie4e4d0842012-03-11 07:00:24 +00004681 << Correction.getQuoted(SemaRef.getLangOpts());
Kaelyn Uhrain10553932011-10-10 18:01:37 +00004682 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004683 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00004684 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00004685 } else
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00004686 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00004687 }
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00004688 return Result;
John McCall29ae6e52010-10-13 05:45:15 +00004689}
4690
David Blaikied662a792011-10-19 22:56:21 +00004691static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
4692 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004693 switch (D.getDeclSpec().getStorageClassSpec()) {
4694 default: llvm_unreachable("Unknown storage class!");
4695 case DeclSpec::SCS_auto:
4696 case DeclSpec::SCS_register:
4697 case DeclSpec::SCS_mutable:
4698 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4699 diag::err_typecheck_sclass_func);
4700 D.setInvalidType();
4701 break;
4702 case DeclSpec::SCS_unspecified: break;
4703 case DeclSpec::SCS_extern: return SC_Extern;
4704 case DeclSpec::SCS_static: {
4705 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4706 // C99 6.7.1p5:
4707 // The declaration of an identifier for a function that has
4708 // block scope shall have no explicit storage-class specifier
4709 // other than extern
4710 // See also (C++ [dcl.stc]p4).
4711 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4712 diag::err_static_block_func);
4713 break;
4714 } else
4715 return SC_Static;
4716 }
4717 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4718 }
4719
4720 // No explicit storage class has already been returned
4721 return SC_None;
4722}
4723
4724static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4725 DeclContext *DC, QualType &R,
4726 TypeSourceInfo *TInfo,
4727 FunctionDecl::StorageClass SC,
4728 bool &IsVirtualOkay) {
4729 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4730 DeclarationName Name = NameInfo.getName();
4731
4732 FunctionDecl *NewFD = 0;
4733 bool isInline = D.getDeclSpec().isInlineSpecified();
4734 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4735 FunctionDecl::StorageClass SCAsWritten
4736 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4737
David Blaikie4e4d0842012-03-11 07:00:24 +00004738 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004739 // Determine whether the function was written with a
4740 // prototype. This true when:
4741 // - there is a prototype in the declarator, or
4742 // - the type R of the function is some kind of typedef or other reference
4743 // to a type name (which eventually refers to a function type).
4744 bool HasPrototype =
4745 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4746 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4747
David Blaikied662a792011-10-19 22:56:21 +00004748 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00004749 D.getLocStart(), NameInfo, R,
David Blaikied662a792011-10-19 22:56:21 +00004750 TInfo, SC, SCAsWritten, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004751 HasPrototype);
4752 if (D.isInvalidType())
4753 NewFD->setInvalidDecl();
4754
4755 // Set the lexical context.
4756 NewFD->setLexicalDeclContext(SemaRef.CurContext);
4757
4758 return NewFD;
4759 }
4760
4761 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4762 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4763
4764 // Check that the return type is not an abstract class type.
4765 // For record types, this is done by the AbstractClassUsageDiagnoser once
4766 // the class has been completely parsed.
4767 if (!DC->isRecord() &&
4768 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4769 R->getAs<FunctionType>()->getResultType(),
4770 diag::err_abstract_type_in_decl,
4771 SemaRef.AbstractReturnType))
4772 D.setInvalidType();
4773
4774 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4775 // This is a C++ constructor declaration.
4776 assert(DC->isRecord() &&
4777 "Constructors can only be declared in a member context");
4778
4779 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4780 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004781 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004782 R, TInfo, isExplicit, isInline,
4783 /*isImplicitlyDeclared=*/false,
4784 isConstexpr);
4785
4786 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4787 // This is a C++ destructor declaration.
4788 if (DC->isRecord()) {
4789 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4790 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4791 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4792 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00004793 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004794 NameInfo, R, TInfo, isInline,
4795 /*isImplicitlyDeclared=*/false);
4796
4797 // If the class is complete, then we now create the implicit exception
4798 // specification. If the class is incomplete or dependent, we can't do
4799 // it yet.
David Blaikie4e4d0842012-03-11 07:00:24 +00004800 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004801 Record->getDefinition() && !Record->isBeingDefined() &&
4802 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4803 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4804 }
4805
4806 IsVirtualOkay = true;
4807 return NewDD;
4808
4809 } else {
4810 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4811 D.setInvalidType();
4812
4813 // Create a FunctionDecl to satisfy the function definition parsing
4814 // code path.
4815 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00004816 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004817 D.getIdentifierLoc(), Name, R, TInfo,
4818 SC, SCAsWritten, isInline,
4819 /*hasPrototype=*/true, isConstexpr);
4820 }
4821
4822 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4823 if (!DC->isRecord()) {
4824 SemaRef.Diag(D.getIdentifierLoc(),
4825 diag::err_conv_function_not_member);
4826 return 0;
4827 }
4828
4829 SemaRef.CheckConversionDeclarator(D, R, SC);
4830 IsVirtualOkay = true;
4831 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004832 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004833 R, TInfo, isInline, isExplicit,
4834 isConstexpr, SourceLocation());
4835
4836 } else if (DC->isRecord()) {
4837 // If the name of the function is the same as the name of the record,
4838 // then this must be an invalid constructor that has a return type.
4839 // (The parser checks for a return type and makes the declarator a
4840 // constructor if it has no return type).
4841 if (Name.getAsIdentifierInfo() &&
4842 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4843 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4844 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4845 << SourceRange(D.getIdentifierLoc());
4846 return 0;
4847 }
4848
4849 bool isStatic = SC == SC_Static;
4850
4851 // [class.free]p1:
4852 // Any allocation function for a class T is a static member
4853 // (even if not explicitly declared static).
4854 if (Name.getCXXOverloadedOperator() == OO_New ||
4855 Name.getCXXOverloadedOperator() == OO_Array_New)
4856 isStatic = true;
4857
4858 // [class.free]p6 Any deallocation function for a class X is a static member
4859 // (even if not explicitly declared static).
4860 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4861 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4862 isStatic = true;
4863
4864 IsVirtualOkay = !isStatic;
4865
4866 // This is a C++ method declaration.
4867 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004868 D.getLocStart(), NameInfo, R,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004869 TInfo, isStatic, SCAsWritten, isInline,
4870 isConstexpr, SourceLocation());
4871
4872 } else {
4873 // Determine whether the function was written with a
4874 // prototype. This true when:
4875 // - we're in C++ (where every function has a prototype),
4876 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00004877 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004878 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4879 true/*HasPrototype*/, isConstexpr);
4880 }
4881}
4882
Mike Stump1eb44332009-09-09 15:08:12 +00004883NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00004884Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004885 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00004886 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004887 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004888 QualType R = TInfo->getType();
4889
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004890 assert(R.getTypePtr()->isFunctionType());
4891
Abramo Bagnara25777432010-08-11 22:01:17 +00004892 // TODO: consider using NameInfo for diagnostic.
4893 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4894 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004895 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004896
Eli Friedman63054b32009-04-19 20:27:55 +00004897 if (D.getDeclSpec().isThreadSpecified())
4898 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4899
Chris Lattnerbb749822009-04-11 19:17:25 +00004900 // Do not allow returning a objc interface by-value.
John McCallc12c5bb2010-05-15 11:32:37 +00004901 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattnerbb749822009-04-11 19:17:25 +00004902 Diag(D.getIdentifierLoc(),
4903 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00004904 << R->getAs<FunctionType>()->getResultType()
4905 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004906
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00004907 QualType T = R->getAs<FunctionType>()->getResultType();
4908 T = Context.getObjCObjectPointerType(T);
4909 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4910 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4911 R = Context.getFunctionType(T, FPT->arg_type_begin(),
4912 FPT->getNumArgs(), EPI);
4913 }
4914 else if (isa<FunctionNoProtoType>(R))
4915 R = Context.getFunctionNoProtoType(T);
Chris Lattnerbb749822009-04-11 19:17:25 +00004916 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004917
Douglas Gregor3922ed02010-12-10 19:28:19 +00004918 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00004919 FunctionTemplateDecl *FunctionTemplate = 0;
4920 bool isExplicitSpecialization = false;
4921 bool isFunctionTemplateSpecialization = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004922 bool isDependentClassScopeExplicitSpecialization = false;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004923 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004924
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004925 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4926 isVirtualOkay);
4927 if (!NewFD) return 0;
4928
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004929 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4930 NewFD->setTopLevelDeclInObjCContainer();
4931
David Blaikie4e4d0842012-03-11 07:00:24 +00004932 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004933 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00004934 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4935 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004936 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00004937 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004938 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00004939 // C++ [class.friend]p5
4940 // A function can be defined in a friend declaration of a
4941 // class . . . . Such a function is implicitly inline.
4942 NewFD->setImplicitlyInline();
4943 }
4944
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004945 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004946 isExplicitSpecialization = false;
4947 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004948 if (D.isInvalidType())
4949 NewFD->setInvalidDecl();
4950
4951 // Set the lexical context. If the declarator has a C++
4952 // scope specifier, or is the object of a friend declaration, the
4953 // lexical context will be different from the semantic context.
4954 NewFD->setLexicalDeclContext(CurContext);
Douglas Gregor45fa5602011-11-07 20:56:01 +00004955
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004956 // Match up the template parameter lists with the scope specifier, then
4957 // determine whether we have a template or a template specialization.
4958 bool Invalid = false;
4959 if (TemplateParameterList *TemplateParams
Douglas Gregorcb710a42011-03-04 22:45:55 +00004960 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar96a00142012-03-09 18:35:03 +00004961 D.getDeclSpec().getLocStart(),
Douglas Gregorc8406492011-05-10 18:27:06 +00004962 D.getIdentifierLoc(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004963 D.getCXXScopeSpec(),
John McCall6102ca12010-10-16 06:59:13 +00004964 TemplateParamLists.get(),
4965 TemplateParamLists.size(),
4966 isFriend,
4967 isExplicitSpecialization,
4968 Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004969 if (TemplateParams->size() > 0) {
4970 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00004971
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004972 // Check that we can declare a template here.
4973 if (CheckTemplateDeclScope(S, TemplateParams))
4974 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004975
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004976 // A destructor cannot be a template.
4977 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4978 Diag(NewFD->getLocation(), diag::err_destructor_template);
4979 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00004980 }
Douglas Gregor20606502011-10-14 15:31:12 +00004981
4982 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00004983 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00004984 // now that we know what the current instantiation is.
4985 if (DC->isDependentContext()) {
4986 ContextRAII SavedContext(*this, DC);
4987 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
4988 Invalid = true;
4989 }
4990
John McCall5fd378b2010-03-24 08:27:58 +00004991
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00004992 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4993 NewFD->getLocation(),
4994 Name, TemplateParams,
4995 NewFD);
4996 FunctionTemplate->setLexicalDeclContext(CurContext);
4997 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4998
4999 // For source fidelity, store the other template param lists.
5000 if (TemplateParamLists.size() > 1) {
5001 NewFD->setTemplateParameterListsInfo(Context,
5002 TemplateParamLists.size() - 1,
5003 TemplateParamLists.release());
5004 }
5005 } else {
5006 // This is a function template specialization.
5007 isFunctionTemplateSpecialization = true;
5008 // For source fidelity, store all the template param lists.
5009 NewFD->setTemplateParameterListsInfo(Context,
5010 TemplateParamLists.size(),
5011 TemplateParamLists.release());
5012
5013 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5014 if (isFriend) {
5015 // We want to remove the "template<>", found here.
5016 SourceRange RemoveRange = TemplateParams->getSourceRange();
5017
5018 // If we remove the template<> and the name is not a
5019 // template-id, we're actually silently creating a problem:
5020 // the friend declaration will refer to an untemplated decl,
5021 // and clearly the user wants a template specialization. So
5022 // we need to insert '<>' after the name.
5023 SourceLocation InsertLoc;
5024 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5025 InsertLoc = D.getName().getSourceRange().getEnd();
5026 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5027 }
5028
5029 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5030 << Name << RemoveRange
5031 << FixItHint::CreateRemoval(RemoveRange)
5032 << FixItHint::CreateInsertion(InsertLoc, "<>");
5033 }
5034 }
5035 }
5036 else {
5037 // All template param lists were matched against the scope specifier:
5038 // this is NOT (an explicit specialization of) a template.
5039 if (TemplateParamLists.size() > 0)
5040 // For source fidelity, store all the template param lists.
5041 NewFD->setTemplateParameterListsInfo(Context,
5042 TemplateParamLists.size(),
5043 TemplateParamLists.release());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005044 }
5045
5046 if (Invalid) {
5047 NewFD->setInvalidDecl();
5048 if (FunctionTemplate)
5049 FunctionTemplate->setInvalidDecl();
5050 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00005051
Richard Smith1d7bcf42012-01-06 01:31:20 +00005052 // If we see "T var();" at block scope, where T is a class type, it is
5053 // probably an attempt to initialize a variable, not a function declaration.
5054 // We don't catch this case earlier, since there is no ambiguity here.
5055 if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
5056 CurContext->isFunctionOrMethod() &&
5057 D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
5058 D.getDeclSpec().getStorageClassSpecAsWritten()
5059 == DeclSpec::SCS_unspecified) {
5060 QualType T = R->getAs<FunctionType>()->getResultType();
5061 DeclaratorChunk &C = D.getTypeObject(0);
Richard Smith2f0e88a2012-01-06 02:30:50 +00005062 if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
Richard Smith1d7bcf42012-01-06 01:31:20 +00005063 !C.Fun.TrailingReturnType &&
5064 C.Fun.getExceptionSpecType() == EST_None) {
Richard Smith7984de32012-01-12 23:53:29 +00005065 SourceRange ParenRange(C.Loc, C.EndLoc);
5066 Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5067
5068 // If the declaration looks like:
5069 // T var1,
5070 // f();
5071 // and name lookup finds a function named 'f', then the ',' was
5072 // probably intended to be a ';'.
5073 if (!D.isFirstDeclarator() && D.getIdentifier()) {
5074 FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5075 FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5076 if (Comma.getFileID() != Name.getFileID() ||
5077 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5078 LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5079 LookupOrdinaryName);
5080 if (LookupName(Result, S))
5081 Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5082 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5083 }
5084 }
5085 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5086 // Empty parens mean value-initialization, and no parens mean default
5087 // initialization. These are equivalent if the default constructor is
5088 // user-provided, or if zero-initialization is a no-op.
Richard Smithf0375412012-01-13 02:14:39 +00005089 if (RD && RD->hasDefinition() &&
5090 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
Richard Smith7984de32012-01-12 23:53:29 +00005091 Diag(C.Loc, diag::note_empty_parens_default_ctor)
5092 << FixItHint::CreateRemoval(ParenRange);
5093 else if (const char *Init = getFixItZeroInitializerForType(T))
5094 Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5095 << FixItHint::CreateReplacement(ParenRange, Init);
5096 else if (LangOpts.CPlusPlus0x)
5097 Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5098 << FixItHint::CreateReplacement(ParenRange, "{}");
Richard Smith1d7bcf42012-01-06 01:31:20 +00005099 }
5100 }
5101
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005102 // C++ [dcl.fct.spec]p5:
5103 // The virtual specifier shall only be used in declarations of
5104 // nonstatic class member functions that appear within a
5105 // member-specification of a class declaration; see 10.3.
5106 //
5107 if (isVirtual && !NewFD->isInvalidDecl()) {
5108 if (!isVirtualOkay) {
5109 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5110 diag::err_virtual_non_function);
5111 } else if (!CurContext->isRecord()) {
5112 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00005113 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5114 diag::err_virtual_out_of_class)
5115 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5116 } else if (NewFD->getDescribedFunctionTemplate()) {
5117 // C++ [temp.mem]p3:
5118 // A member function template shall not be virtual.
5119 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5120 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005121 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5122 } else {
5123 // Okay: Add virtual to the method.
5124 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00005125 }
Douglas Gregorc5c903a2009-06-24 00:23:40 +00005126 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00005127
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005128 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00005129 // The inline specifier shall not appear on a block scope function
5130 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005131 if (isInline && !NewFD->isInvalidDecl()) {
5132 if (CurContext->isFunctionOrMethod()) {
5133 // 'inline' is not allowed on block scope function declaration.
5134 Diag(D.getDeclSpec().getInlineSpecLoc(),
5135 diag::err_inline_declaration_block_scope) << Name
5136 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5137 }
5138 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00005139
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005140 // C++ [dcl.fct.spec]p6:
5141 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00005142 // constructor or conversion function within its class definition;
5143 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005144 if (isExplicit && !NewFD->isInvalidDecl()) {
5145 if (!CurContext->isRecord()) {
5146 // 'explicit' was specified outside of the class.
5147 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5148 diag::err_explicit_out_of_class)
5149 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5150 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5151 !isa<CXXConversionDecl>(NewFD)) {
5152 // 'explicit' was specified on a function that wasn't a constructor
5153 // or conversion function.
5154 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5155 diag::err_explicit_non_ctor_or_conv_function)
5156 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5157 }
5158 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00005159
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005160 if (isConstexpr) {
5161 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5162 // are implicitly inline.
5163 NewFD->setImplicitlyInline();
5164
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005165 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5166 // be either constructors or to return a literal type. Therefore,
5167 // destructors cannot be declared constexpr.
5168 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00005169 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005170 }
5171
Douglas Gregor8d267c52011-09-09 02:06:17 +00005172 // If __module_private__ was specified, mark the function accordingly.
5173 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00005174 if (isFunctionTemplateSpecialization) {
5175 SourceLocation ModulePrivateLoc
5176 = D.getDeclSpec().getModulePrivateSpecLoc();
5177 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5178 << 0
5179 << FixItHint::CreateRemoval(ModulePrivateLoc);
5180 } else {
5181 NewFD->setModulePrivate();
5182 if (FunctionTemplate)
5183 FunctionTemplate->setModulePrivate();
5184 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005185 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005186
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005187 if (isFriend) {
5188 // For now, claim that the objects have no previous declaration.
5189 if (FunctionTemplate) {
5190 FunctionTemplate->setObjectOfFriendDecl(false);
5191 FunctionTemplate->setAccess(AS_public);
5192 }
5193 NewFD->setObjectOfFriendDecl(false);
5194 NewFD->setAccess(AS_public);
5195 }
5196
Douglas Gregor45fa5602011-11-07 20:56:01 +00005197 // If a function is defined as defaulted or deleted, mark it as such now.
5198 switch (D.getFunctionDefinitionKind()) {
5199 case FDK_Declaration:
5200 case FDK_Definition:
5201 break;
5202
5203 case FDK_Defaulted:
5204 NewFD->setDefaulted();
5205 break;
5206
5207 case FDK_Deleted:
5208 NewFD->setDeletedAsWritten();
5209 break;
5210 }
5211
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005212 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5213 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00005214 // C++ [class.mfct]p2:
5215 // A member function may be defined (8.4) in its class definition, in
5216 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00005217 NewFD->setImplicitlyInline();
5218 }
5219
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005220 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5221 !CurContext->isRecord()) {
5222 // C++ [class.static]p1:
5223 // A data or function member of a class may be declared static
5224 // in a class definition, in which case it is a static member of
5225 // the class.
5226
5227 // Complain about the 'static' specifier if it's on an out-of-line
5228 // member function definition.
5229 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5230 diag::err_static_out_of_line)
5231 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5232 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005233 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00005234
5235 // Filter out previous declarations that don't match the scope.
5236 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5237 isExplicitSpecialization ||
5238 isFunctionTemplateSpecialization);
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005239
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005240 // Handle GNU asm-label extension (encoded as an attribute).
5241 if (Expr *E = (Expr*) D.getAsmLabel()) {
5242 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005243 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00005244 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5245 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00005246 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5247 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5248 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5249 if (I != ExtnameUndeclaredIdentifiers.end()) {
5250 NewFD->addAttr(I->second);
5251 ExtnameUndeclaredIdentifiers.erase(I);
5252 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005253 }
5254
Chris Lattner2dbd2852009-04-25 06:12:16 +00005255 // Copy the parameter declarations from the declarator D to the function
5256 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005257 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00005258 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005259 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005260
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005261 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5262 // function that takes no arguments, not a function that takes a
5263 // single void argument.
5264 // We let through "const void" here because Sema::GetTypeForDeclarator
5265 // already checks for that case.
5266 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5267 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005268 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00005269 // Empty arg list, don't push any params.
John McCalld226f652010-08-21 09:40:31 +00005270 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005271
5272 // In C++, the empty parameter-type-list must be spelled "void"; a
5273 // typedef of void is not permitted.
David Blaikie4e4d0842012-03-11 07:00:24 +00005274 if (getLangOpts().CPlusPlus &&
Richard Smith162e1c12011-04-15 14:24:37 +00005275 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5276 bool IsTypeAlias = false;
5277 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5278 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005279 else if (const TemplateSpecializationType *TST =
5280 Param->getType()->getAs<TemplateSpecializationType>())
5281 IsTypeAlias = TST->isTypeAlias();
Richard Smith162e1c12011-04-15 14:24:37 +00005282 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5283 << IsTypeAlias;
5284 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005285 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00005286 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00005287 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00005288 assert(Param->getDeclContext() != NewFD && "Was set before ?");
5289 Param->setDeclContext(NewFD);
5290 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00005291
5292 if (Param->isInvalidDecl())
5293 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00005294 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005295 }
Mike Stump1eb44332009-09-09 15:08:12 +00005296
John McCall183700f2009-09-21 23:43:11 +00005297 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00005298 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005299 // following example, we'll need to synthesize (unnamed)
5300 // parameters for use in the declaration.
5301 //
5302 // @code
5303 // typedef void fn(int);
5304 // fn f;
5305 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00005306
Chris Lattner1ad9b282009-04-25 06:03:53 +00005307 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00005308 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5309 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00005310 ParmVarDecl *Param =
5311 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00005312 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00005313 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005314 }
Chris Lattner84bb9442009-04-25 18:38:18 +00005315 } else {
5316 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5317 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005318 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00005319
Chris Lattner2dbd2852009-04-25 06:12:16 +00005320 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00005321 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00005322
James Molloy16f1f712012-02-29 10:24:19 +00005323 // Find all anonymous symbols defined during the declaration of this function
5324 // and add to NewFD. This lets us track decls such 'enum Y' in:
5325 //
5326 // void f(enum Y {AA} x) {}
5327 //
5328 // which would otherwise incorrectly end up in the translation unit scope.
5329 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5330 DeclsInPrototypeScope.clear();
5331
Peter Collingbournec80e8112011-01-21 02:08:54 +00005332 // Process the non-inheritable attributes on this declaration.
5333 ProcessDeclAttributes(S, NewFD, D,
5334 /*NonInheritable=*/true, /*Inheritable=*/false);
5335
Richard Smithb03a9df2012-03-13 05:56:40 +00005336 // Functions returning a variably modified type violate C99 6.7.5.2p2
5337 // because all functions have linkage.
5338 if (!NewFD->isInvalidDecl() &&
5339 NewFD->getResultType()->isVariablyModifiedType()) {
5340 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5341 NewFD->setInvalidDecl();
5342 }
5343
David Blaikie4e4d0842012-03-11 07:00:24 +00005344 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005345 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00005346 bool isExplicitSpecialization=false;
David Blaikie14068e82011-09-08 06:33:04 +00005347 if (!NewFD->isInvalidDecl()) {
Richard Smithb03a9df2012-03-13 05:56:40 +00005348 if (NewFD->isMain())
5349 CheckMain(NewFD, D.getDeclSpec());
5350 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5351 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00005352 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005353 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005354 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5355 "previous declaration set still overloaded");
5356 } else {
5357 // If the declarator is a template-id, translate the parser's template
5358 // argument list into our AST format.
5359 bool HasExplicitTemplateArgs = false;
5360 TemplateArgumentListInfo TemplateArgs;
5361 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5362 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5363 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5364 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5365 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5366 TemplateId->getTemplateArgs(),
5367 TemplateId->NumArgs);
5368 translateTemplateArguments(TemplateArgsPtr,
5369 TemplateArgs);
5370 TemplateArgsPtr.release();
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005371
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005372 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005373
Douglas Gregor89b9f102011-06-06 15:22:55 +00005374 if (NewFD->isInvalidDecl()) {
5375 HasExplicitTemplateArgs = false;
5376 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00005377 // Function template with explicit template arguments.
5378 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5379 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5380
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005381 HasExplicitTemplateArgs = false;
5382 } else if (!isFunctionTemplateSpecialization &&
5383 !D.getDeclSpec().isFriendSpecified()) {
5384 // We have encountered something that the user meant to be a
5385 // specialization (because it has explicitly-specified template
5386 // arguments) but that was not introduced with a "template<>" (or had
5387 // too few of them).
5388 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5389 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5390 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00005391 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00005392 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005393 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00005394 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005395 // "friend void foo<>(int);" is an implicit specialization decl.
5396 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00005397 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005398 } else if (isFriend && isFunctionTemplateSpecialization) {
5399 // This combination is only possible in a recovery case; the user
5400 // wrote something like:
5401 // template <> friend void foo(int);
5402 // which we're recovering from as if the user had written:
5403 // friend void foo<>(int);
5404 // Go ahead and fake up a template id.
5405 HasExplicitTemplateArgs = true;
5406 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5407 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005408 }
John McCall29ae6e52010-10-13 05:45:15 +00005409
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005410 // If it's a friend (and only if it's a friend), it's possible
5411 // that either the specialized function type or the specialized
5412 // template is dependent, and therefore matching will fail. In
5413 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00005414 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005415 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00005416 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5417 TemplateSpecializationType::anyDependentTemplateArguments(
5418 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5419 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005420 assert(HasExplicitTemplateArgs &&
5421 "friend function specialization without template args");
5422 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5423 Previous))
5424 NewFD->setInvalidDecl();
5425 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00005426 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00005427 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00005428 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00005429 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00005430 diag::ext_function_specialization_in_class :
5431 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00005432 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00005433 } else if (CheckFunctionTemplateSpecialization(NewFD,
5434 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5435 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005436 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00005437
5438 // C++ [dcl.stc]p1:
5439 // A storage-class-specifier shall not be specified in an explicit
5440 // specialization (14.7.3)
5441 if (SC != SC_None) {
Douglas Gregor0f9dc862011-06-17 05:09:08 +00005442 if (SC != NewFD->getStorageClass())
5443 Diag(NewFD->getLocation(),
5444 diag::err_explicit_specialization_inconsistent_storage_class)
5445 << SC
5446 << FixItHint::CreateRemoval(
5447 D.getDeclSpec().getStorageClassSpecLoc());
5448
5449 else
5450 Diag(NewFD->getLocation(),
5451 diag::ext_explicit_specialization_storage_class)
5452 << FixItHint::CreateRemoval(
5453 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00005454 }
5455
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005456 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5457 if (CheckMemberSpecialization(NewFD, Previous))
5458 NewFD->setInvalidDecl();
5459 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005460
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005461 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00005462 if (!isDependentClassScopeExplicitSpecialization) {
5463 if (NewFD->isInvalidDecl()) {
5464 // If this is a class member, mark the class invalid immediately.
5465 // This avoids some consistency errors later.
5466 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5467 methodDecl->getParent()->setInvalidDecl();
5468 } else {
5469 if (NewFD->isMain())
5470 CheckMain(NewFD, D.getDeclSpec());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005471 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5472 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00005473 }
5474 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005475
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005476 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005477 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5478 "previous declaration set still overloaded");
5479
5480 NamedDecl *PrincipalDecl = (FunctionTemplate
5481 ? cast<NamedDecl>(FunctionTemplate)
5482 : NewFD);
5483
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005484 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005485 AccessSpecifier Access = AS_public;
5486 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00005487 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005488
5489 NewFD->setAccess(Access);
5490 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5491
5492 PrincipalDecl->setObjectOfFriendDecl(true);
5493 }
5494
5495 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5496 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5497 PrincipalDecl->setNonMemberOperator();
5498
5499 // If we have a function template, check the template parameter
5500 // list. This will check and merge default template arguments.
5501 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00005502 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00005503 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005504 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00005505 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00005506 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005507 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00005508 ? TPC_FriendFunctionTemplateDefinition
5509 : TPC_FriendFunctionTemplate)
5510 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00005511 DC && DC->isRecord() &&
5512 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00005513 ? TPC_ClassTemplateMember
5514 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005515 }
5516
5517 if (NewFD->isInvalidDecl()) {
5518 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005519 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00005520 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005521 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005522 // Fake up an access specifier if it's supposed to be a class member.
5523 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5524 NewFD->setAccess(AS_public);
5525
5526 // Qualified decls generally require a previous declaration.
5527 if (D.getCXXScopeSpec().isSet()) {
5528 // ...with the major exception of templated-scope or
5529 // dependent-scope friend declarations.
5530
5531 // TODO: we currently also suppress this check in dependent
5532 // contexts because (1) the parameter depth will be off when
5533 // matching friend templates and (2) we might actually be
5534 // selecting a friend based on a dependent factor. But there
5535 // are situations where these conditions don't apply and we
5536 // can actually do this check immediately.
5537 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005538 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005539 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5540 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00005541 // ignore these
5542 } else {
5543 // The user tried to provide an out-of-line definition for a
5544 // function that is a member of a class or namespace, but there
5545 // was no such member function declared (C++ [class.mfct]p2,
5546 // C++ [namespace.memdef]p2). For example:
5547 //
5548 // class X {
5549 // void f() const;
5550 // };
5551 //
5552 // void X::f() { } // ill-formed
5553 //
5554 // Complain about this problem, and attempt to suggest close
5555 // matches (e.g., those that differ only in cv-qualifiers and
5556 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005557
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005558 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00005559 NewFD,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005560 ExtraArgs)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005561 AddToScope = ExtraArgs.AddToScope;
5562 return Result;
5563 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00005564 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005565
5566 // Unqualified local friend declarations are required to resolve
5567 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00005568 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005569 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00005570 NewFD,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005571 ExtraArgs)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005572 AddToScope = ExtraArgs.AddToScope;
5573 return Result;
5574 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00005575 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005576
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005577 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005578 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00005579 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005580 // An out-of-line member function declaration must also be a
5581 // definition (C++ [dcl.meaning]p1).
5582 // Note that this is not the case for explicit specializations of
5583 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00005584 // C++ [temp.expl.spec]p2. We also allow these declarations as an
5585 // extension for compatibility with old SWIG code which likes to
5586 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005587 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5588 << D.getCXXScopeSpec().getRange();
5589 }
5590 }
Sean Hunte4246a62011-05-12 06:15:49 +00005591
5592
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005593 // Handle attributes. We need to have merged decls when handling attributes
5594 // (for example to check for conflicts, etc).
5595 // FIXME: This needs to happen before we merge declarations. Then,
5596 // let attribute merging cope with attribute conflicts.
Peter Collingbournec80e8112011-01-21 02:08:54 +00005597 ProcessDeclAttributes(S, NewFD, D,
5598 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynn478fbc62009-07-25 22:29:44 +00005599
5600 // attributes declared post-definition are currently ignored
Sean Huntcf807c42010-08-18 23:23:40 +00005601 // FIXME: This should happen during attribute merging
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005602 if (D.isRedeclaration() && Previous.isSingleResult()) {
John McCall68263142009-11-18 22:49:29 +00005603 const FunctionDecl *Def;
5604 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Sean Hunt10620eb2011-05-06 20:44:56 +00005605 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00005606 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5607 Diag(Def->getLocation(), diag::note_previous_definition);
5608 }
5609 }
5610
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005611 AddKnownFunctionAttributes(NewFD);
5612
Douglas Gregord9455382010-08-06 13:50:58 +00005613 if (NewFD->hasAttr<OverloadableAttr>() &&
5614 !NewFD->getType()->getAs<FunctionProtoType>()) {
5615 Diag(NewFD->getLocation(),
5616 diag::err_attribute_overloadable_no_prototype)
5617 << NewFD;
5618
5619 // Turn this into a variadic function with no parameters.
5620 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalle23cf432010-12-14 08:05:40 +00005621 FunctionProtoType::ExtProtoInfo EPI;
5622 EPI.Variadic = true;
5623 EPI.ExtInfo = FT->getExtInfo();
5624
5625 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00005626 NewFD->setType(R);
5627 }
5628
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005629 // If there's a #pragma GCC visibility in scope, and this isn't a class
5630 // member, set the visibility of this function.
5631 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5632 AddPushedVisibilityAttribute(NewFD);
5633
John McCall8dfac0b2011-09-30 05:12:12 +00005634 // If there's a #pragma clang arc_cf_code_audited in scope, consider
5635 // marking the function.
5636 AddCFAuditedAttribute(NewFD);
5637
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005638 // If this is a locally-scoped extern C function, update the
5639 // map of such names.
Douglas Gregor48a83b52009-09-12 00:17:51 +00005640 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnereaaebc72009-04-25 08:06:05 +00005641 && !NewFD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00005642 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005643
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00005644 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00005645 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00005646
David Blaikie4e4d0842012-03-11 07:00:24 +00005647 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005648 if (FunctionTemplate) {
5649 if (NewFD->isInvalidDecl())
5650 FunctionTemplate->setInvalidDecl();
5651 return FunctionTemplate;
5652 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005653 }
Mike Stump1eb44332009-09-09 15:08:12 +00005654
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005655 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00005656
David Blaikie4e4d0842012-03-11 07:00:24 +00005657 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00005658 if (IdentifierInfo *II = NewFD->getIdentifier())
5659 if (!NewFD->isInvalidDecl() &&
5660 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5661 if (II->isStr("cudaConfigureCall")) {
5662 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5663 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5664
5665 Context.setcudaConfigureCallDecl(NewFD);
5666 }
5667 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00005668
5669 // Here we have an function template explicit specialization at class scope.
5670 // The actually specialization will be postponed to template instatiation
5671 // time via the ClassScopeFunctionSpecializationDecl node.
5672 if (isDependentClassScopeExplicitSpecialization) {
5673 ClassScopeFunctionSpecializationDecl *NewSpec =
5674 ClassScopeFunctionSpecializationDecl::Create(
5675 Context, CurContext, SourceLocation(),
5676 cast<CXXMethodDecl>(NewFD));
5677 CurContext->addDecl(NewSpec);
5678 AddToScope = false;
5679 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00005680
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005681 return NewFD;
5682}
5683
5684/// \brief Perform semantic checking of a new function declaration.
5685///
5686/// Performs semantic analysis of the new function declaration
5687/// NewFD. This routine performs all semantic checking that does not
5688/// require the actual declarator involved in the declaration, and is
5689/// used both for the declaration of functions as they are parsed
5690/// (called via ActOnDeclarator) and for the declaration of functions
5691/// that have been instantiated via C++ template instantiation (called
5692/// via InstantiateDecl).
5693///
Douglas Gregorfd056bc2009-10-13 16:30:37 +00005694/// \param IsExplicitSpecialiation whether this new function declaration is
5695/// an explicit specialization of the previous declaration.
5696///
Chris Lattnereaaebc72009-04-25 08:06:05 +00005697/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005698///
5699/// Returns true if the function declaration is a redeclaration.
5700bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00005701 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005702 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00005703 assert(!NewFD->getResultType()->isVariablyModifiedType()
5704 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00005705
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005706 // Check for a previous declaration of this name.
John McCall68263142009-11-18 22:49:29 +00005707 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00005708 // Since we did not find anything by this name and we're declaring
5709 // an extern "C" function, look for a non-visible extern "C"
5710 // declaration with the same name.
5711 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorec12ce22011-07-28 14:20:37 +00005712 = findLocallyScopedExternalDecl(NewFD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00005713 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00005714 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00005715 }
5716
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005717 bool Redeclaration = false;
5718
Douglas Gregor04495c82009-02-24 01:23:02 +00005719 // Merge or overload the declaration with an existing declaration of
5720 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00005721 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00005722 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005723 // a declaration that requires merging. If it's an overload,
5724 // there's no more work to do here; we'll just add the new
5725 // function to the scope.
Douglas Gregorae170942009-02-13 00:26:38 +00005726
John McCall68263142009-11-18 22:49:29 +00005727 NamedDecl *OldDecl = 0;
John McCall871b2e72009-12-09 03:35:25 +00005728 if (!AllowOverloadingOfFunction(Previous, Context)) {
5729 Redeclaration = true;
5730 OldDecl = Previous.getFoundDecl();
5731 } else {
John McCallad00b772010-06-16 08:42:20 +00005732 switch (CheckOverload(S, NewFD, Previous, OldDecl,
5733 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00005734 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005735 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00005736 break;
5737
5738 case Ovl_NonFunction:
5739 Redeclaration = true;
5740 break;
5741
5742 case Ovl_Overload:
5743 Redeclaration = false;
5744 break;
John McCall68263142009-11-18 22:49:29 +00005745 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00005746
David Blaikie4e4d0842012-03-11 07:00:24 +00005747 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00005748 // If a function name is overloadable in C, then every function
5749 // with that name must be marked "overloadable".
5750 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5751 << Redeclaration << NewFD;
5752 NamedDecl *OverloadedDecl = 0;
5753 if (Redeclaration)
5754 OverloadedDecl = OldDecl;
5755 else if (!Previous.empty())
5756 OverloadedDecl = Previous.getRepresentativeDecl();
5757 if (OverloadedDecl)
5758 Diag(OverloadedDecl->getLocation(),
5759 diag::note_attribute_overloadable_prev_overload);
5760 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5761 Context));
5762 }
John McCall68263142009-11-18 22:49:29 +00005763 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005764
John McCall68263142009-11-18 22:49:29 +00005765 if (Redeclaration) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00005766 // NewFD and OldDecl represent declarations that need to be
Mike Stump1eb44332009-09-09 15:08:12 +00005767 // merged.
James Molloy9cda03f2012-03-13 08:55:35 +00005768 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005769 NewFD->setInvalidDecl();
5770 return Redeclaration;
5771 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005772
John McCall68263142009-11-18 22:49:29 +00005773 Previous.clear();
5774 Previous.addDecl(OldDecl);
5775
Douglas Gregore53060f2009-06-25 22:08:12 +00005776 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregor37d681852009-10-12 22:27:17 +00005777 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
David Blaikied662a792011-10-19 22:56:21 +00005778 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregor37d681852009-10-12 22:27:17 +00005779 FunctionTemplateDecl *NewTemplateDecl
5780 = NewFD->getDescribedFunctionTemplate();
5781 assert(NewTemplateDecl && "Template/non-template mismatch");
5782 if (CXXMethodDecl *Method
5783 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5784 Method->setAccess(OldTemplateDecl->getAccess());
5785 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5786 }
Douglas Gregorfd056bc2009-10-13 16:30:37 +00005787
5788 // If this is an explicit specialization of a member that is a function
5789 // template, mark it as a member specialization.
5790 if (IsExplicitSpecialization &&
5791 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5792 NewTemplateDecl->setMemberSpecialization();
5793 assert(OldTemplateDecl->isMemberSpecialization());
5794 }
Douglas Gregor6311d2b2011-09-09 18:32:39 +00005795
Douglas Gregor37d681852009-10-12 22:27:17 +00005796 } else {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00005797 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5798 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregore53060f2009-06-25 22:08:12 +00005799 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00005800 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005801 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00005802 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005803
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005804 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00005805 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005806 // C++-specific checks.
5807 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5808 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00005809 } else if (CXXDestructorDecl *Destructor =
5810 dyn_cast<CXXDestructorDecl>(NewFD)) {
5811 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005812 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00005813
Douglas Gregor4923aa22010-07-02 20:37:36 +00005814 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00005815 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005816 if (!ClassType->isDependentType()) {
5817 DeclarationName Name
5818 = Context.DeclarationNames.getCXXDestructorName(
5819 Context.getCanonicalType(ClassType));
5820 if (NewFD->getDeclName() != Name) {
5821 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005822 NewFD->setInvalidDecl();
5823 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005824 }
5825 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005826 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00005827 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005828 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00005829 }
5830
5831 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00005832 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5833 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005834 !Method->getDescribedFunctionTemplate()) {
5835 if (AddOverriddenMethods(Method->getParent(), Method)) {
5836 // If the function was marked as "static", we have a problem.
5837 if (NewFD->getStorageClass() == SC_Static) {
5838 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5839 << NewFD->getDeclName();
5840 for (CXXMethodDecl::method_iterator
5841 Overridden = Method->begin_overridden_methods(),
5842 OverriddenEnd = Method->end_overridden_methods();
5843 Overridden != OverriddenEnd;
5844 ++Overridden) {
5845 Diag((*Overridden)->getLocation(),
5846 diag::note_overridden_virtual_function);
5847 }
5848 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005849 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005850 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00005851
5852 if (Method->isStatic())
5853 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00005854 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005855
5856 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5857 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005858 CheckOverloadedOperatorDeclaration(NewFD)) {
5859 NewFD->setInvalidDecl();
5860 return Redeclaration;
5861 }
Sean Hunta6c058d2010-01-13 09:01:02 +00005862
5863 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5864 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005865 CheckLiteralOperatorDeclaration(NewFD)) {
5866 NewFD->setInvalidDecl();
5867 return Redeclaration;
5868 }
Sean Hunta6c058d2010-01-13 09:01:02 +00005869
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005870 // In C++, check default arguments now that we have merged decls. Unless
5871 // the lexical context is the class, because in this case this is done
5872 // during delayed parsing anyway.
5873 if (!CurContext->isRecord())
5874 CheckCXXDefaultArguments(NewFD);
Douglas Gregorb68e3992010-12-21 19:47:46 +00005875
5876 // If this function declares a builtin function, check the type of this
5877 // declaration against the expected type for the builtin.
5878 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5879 ASTContext::GetBuiltinTypeError Error;
5880 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5881 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5882 // The type of this function differs from the type of the builtin,
5883 // so forget about the builtin entirely.
5884 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5885 }
5886 }
Aaron Ballman2c0bf242012-02-09 01:21:34 +00005887
5888 // If this function is declared as being extern "C", then check to see if
5889 // the function returns a UDT (class, struct, or union type) that is not C
5890 // compatible, and if it does, warn the user.
5891 if (NewFD->isExternC()) {
5892 QualType R = NewFD->getResultType();
5893 if (!R.isPODType(Context) &&
5894 !R->isVoidType())
5895 Diag( NewFD->getLocation(), diag::warn_return_value_udt )
5896 << NewFD << R;
5897 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00005898 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005899 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00005900}
5901
David Blaikie14068e82011-09-08 06:33:04 +00005902void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00005903 // C++11 [basic.start.main]p3: A program that declares main to be inline,
5904 // static or constexpr is ill-formed.
John McCall13591ed2009-07-25 04:36:53 +00005905 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5906 // shall not appear in a declaration of main.
5907 // static main is not an error under C99, but we should warn about it.
David Blaikie14068e82011-09-08 06:33:04 +00005908 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00005909 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00005910 ? diag::err_static_main : diag::warn_static_main)
5911 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5912 if (FD->isInlineSpecified())
5913 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5914 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Richard Smitha5065862012-02-04 06:10:17 +00005915 if (FD->isConstexpr()) {
5916 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
5917 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
5918 FD->setConstexpr(false);
5919 }
John McCall13591ed2009-07-25 04:36:53 +00005920
5921 QualType T = FD->getType();
5922 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00005923 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005924
John McCall75d8ba32012-02-14 19:50:52 +00005925 // All the standards say that main() should should return 'int'.
5926 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5927 // In C and C++, main magically returns 0 if you fall off the end;
5928 // set the flag which tells us that.
5929 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5930 FD->setHasImplicitReturnZero(true);
5931
5932 // In C with GNU extensions we allow main() to have non-integer return
5933 // type, but we should warn about the extension, and we disable the
5934 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00005935 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00005936 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
5937
5938 // Otherwise, this is just a flat-out error.
5939 } else {
Douglas Gregor5f39f702011-02-19 19:04:23 +00005940 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall13591ed2009-07-25 04:36:53 +00005941 FD->setInvalidDecl(true);
5942 }
5943
5944 // Treat protoless main() as nullary.
5945 if (isa<FunctionNoProtoType>(FT)) return;
5946
5947 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5948 unsigned nparams = FTP->getNumArgs();
5949 assert(FD->getNumParams() == nparams);
5950
John McCall66755862009-12-24 09:58:38 +00005951 bool HasExtraParameters = (nparams > 3);
5952
5953 // Darwin passes an undocumented fourth argument of type char**. If
5954 // other platforms start sprouting these, the logic below will start
5955 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005956 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00005957 HasExtraParameters = false;
5958
5959 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00005960 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5961 FD->setInvalidDecl(true);
5962 nparams = 3;
5963 }
5964
5965 // FIXME: a lot of the following diagnostics would be improved
5966 // if we had some location information about types.
5967
5968 QualType CharPP =
5969 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00005970 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00005971
5972 for (unsigned i = 0; i < nparams; ++i) {
5973 QualType AT = FTP->getArgType(i);
5974
5975 bool mismatch = true;
5976
5977 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5978 mismatch = false;
5979 else if (Expected[i] == CharPP) {
5980 // As an extension, the following forms are okay:
5981 // char const **
5982 // char const * const *
5983 // char * const *
5984
John McCall0953e762009-09-24 19:53:00 +00005985 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00005986 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00005987 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5988 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall13591ed2009-07-25 04:36:53 +00005989 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5990 qs.removeConst();
5991 mismatch = !qs.empty();
5992 }
5993 }
5994
5995 if (mismatch) {
5996 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5997 // TODO: suggest replacing given type with expected type
5998 FD->setInvalidDecl(true);
5999 }
6000 }
6001
6002 if (nparams == 1 && !FD->isInvalidDecl()) {
6003 Diag(FD->getLocation(), diag::warn_main_one_arg);
6004 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00006005
6006 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6007 Diag(FD->getLocation(), diag::err_main_template_decl);
6008 FD->setInvalidDecl();
6009 }
John McCall8c4859a2009-07-24 03:03:21 +00006010}
6011
Eli Friedmanc594b322008-05-20 13:48:25 +00006012bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00006013 // FIXME: Need strict checking. In C89, we need to check for
6014 // any assignment, increment, decrement, function-calls, or
6015 // commas outside of a sizeof. In C99, it's the same list,
6016 // except that the aforementioned are allowed in unevaluated
6017 // expressions. Everything else falls under the
6018 // "may accept other forms of constant expressions" exception.
6019 // (We never end up here for C++, so the constant expression
6020 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00006021 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00006022 return false;
Eli Friedman21298282009-02-26 04:47:58 +00006023 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6024 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00006025 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00006026}
6027
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006028namespace {
6029 // Visits an initialization expression to see if OrigDecl is evaluated in
6030 // its own initialization and throws a warning if it does.
6031 class SelfReferenceChecker
6032 : public EvaluatedExprVisitor<SelfReferenceChecker> {
6033 Sema &S;
6034 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00006035 bool isRecordType;
6036 bool isPODType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006037
6038 public:
6039 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6040
6041 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00006042 S(S), OrigDecl(OrigDecl) {
6043 isPODType = false;
6044 isRecordType = false;
6045 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6046 isPODType = VD->getType().isPODType(S.Context);
6047 isRecordType = VD->getType()->isRecordType();
6048 }
6049 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006050
6051 void VisitExpr(Expr *E) {
6052 if (isa<ObjCMessageExpr>(*E)) return;
Richard Trieu898267f2011-09-01 21:44:13 +00006053 if (isRecordType) {
6054 Expr *expr = E;
6055 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6056 ValueDecl *VD = ME->getMemberDecl();
6057 if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
6058 expr = ME->getBase();
6059 }
6060 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
6061 HandleDeclRefExpr(DRE);
6062 return;
6063 }
6064 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006065 Inherited::VisitExpr(E);
6066 }
6067
Richard Trieu898267f2011-09-01 21:44:13 +00006068 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu47eb8982011-09-07 00:58:53 +00006069 if (E->getType()->canDecayToPointerType()) return;
Richard Trieuffea6b42012-03-08 01:15:31 +00006070 ValueDecl *VD = E->getMemberDecl();
6071 if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
Richard Trieu898267f2011-09-01 21:44:13 +00006072 if (DeclRefExpr *DRE
6073 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6074 HandleDeclRefExpr(DRE);
6075 return;
6076 }
6077 Inherited::VisitMemberExpr(E);
6078 }
6079
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006080 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu898267f2011-09-01 21:44:13 +00006081 if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
6082 (isRecordType && E->getCastKind() == CK_NoOp)) {
6083 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
6084 if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
6085 SubExpr = ME->getBase()->IgnoreParenImpCasts();
6086 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6087 HandleDeclRefExpr(DRE);
6088 return;
6089 }
6090 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006091 Inherited::VisitImplicitCastExpr(E);
6092 }
6093
Richard Trieu898267f2011-09-01 21:44:13 +00006094 void VisitUnaryOperator(UnaryOperator *E) {
6095 // For POD record types, addresses of its own members are well-defined.
6096 if (isRecordType && isPODType) return;
6097 Inherited::VisitUnaryOperator(E);
6098 }
6099
6100 void HandleDeclRefExpr(DeclRefExpr *DRE) {
6101 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006102 if (OrigDecl != ReferenceDecl) return;
6103 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6104 Sema::NotForRedeclaration);
Richard Trieu898267f2011-09-01 21:44:13 +00006105 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Douglas Gregor63fe6812011-05-24 16:02:01 +00006106 S.PDiag(diag::warn_uninit_self_reference_in_init)
Richard Trieu898267f2011-09-01 21:44:13 +00006107 << Result.getLookupName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00006108 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00006109 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006110 }
6111 };
6112}
6113
Richard Trieu898267f2011-09-01 21:44:13 +00006114/// CheckSelfReference - Warns if OrigDecl is used in expression E.
6115void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
6116 SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
6117}
6118
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006119/// AddInitializerToDecl - Adds the initializer Init to the
6120/// declaration dcl. If DirectInit is true, this is C++ direct
6121/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00006122void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6123 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00006124 // If there is no declaration, there was an error parsing it. Just ignore
6125 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00006126 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00006127 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006128
Douglas Gregor021c3b32009-03-11 23:00:04 +00006129 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6130 // With declarators parsed the way they are, the parser cannot
6131 // distinguish between a normal initializer and a pure-specifier.
6132 // Thus this grotesque test.
6133 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00006134 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00006135 Context.getCanonicalType(IL->getType()) == Context.IntTy)
6136 CheckPureMethod(Method, Init->getSourceRange());
6137 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00006138 Diag(Method->getLocation(), diag::err_member_function_initialization)
6139 << Method->getDeclName() << Init->getSourceRange();
6140 Method->setInvalidDecl();
6141 }
6142 return;
6143 }
6144
Steve Naroff410e3e22007-09-12 20:13:48 +00006145 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6146 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00006147 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6148 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00006149 RealDecl->setInvalidDecl();
6150 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00006151 }
6152
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006153 // Check for self-references within variable initializers.
6154 // Variables declared within a function/method body are handled
6155 // by a dataflow analysis.
6156 if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6157 CheckSelfReference(RealDecl, Init);
6158
6159 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6160
Richard Smith01888722011-12-15 19:20:59 +00006161 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00006162 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006163 Expr *DeduceInit = Init;
6164 // Initializer could be a C++ direct-initializer. Deduction only works if it
6165 // contains exactly one expression.
6166 if (CXXDirectInit) {
6167 if (CXXDirectInit->getNumExprs() == 0) {
6168 // It isn't possible to write this directly, but it is possible to
6169 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00006170 Diag(CXXDirectInit->getLocStart(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006171 diag::err_auto_var_init_no_expression)
6172 << VDecl->getDeclName() << VDecl->getType()
6173 << VDecl->getSourceRange();
6174 RealDecl->setInvalidDecl();
6175 return;
6176 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006177 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006178 diag::err_auto_var_init_multiple_expressions)
6179 << VDecl->getDeclName() << VDecl->getType()
6180 << VDecl->getSourceRange();
6181 RealDecl->setInvalidDecl();
6182 return;
6183 } else {
6184 DeduceInit = CXXDirectInit->getExpr(0);
6185 }
6186 }
Richard Smitha085da82011-03-17 16:11:59 +00006187 TypeSourceInfo *DeducedType = 0;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006188 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006189 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006190 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smitha085da82011-03-17 16:11:59 +00006191 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006192 RealDecl->setInvalidDecl();
6193 return;
6194 }
Richard Smitha085da82011-03-17 16:11:59 +00006195 VDecl->setTypeSourceInfo(DeducedType);
6196 VDecl->setType(DeducedType->getType());
Douglas Gregoree188032012-02-20 20:05:29 +00006197 VDecl->ClearLinkageCache();
6198
John McCallf85e1932011-06-15 23:02:42 +00006199 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00006200 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00006201 VDecl->setInvalidDecl();
6202
Richard Smith34b41d92011-02-20 03:19:35 +00006203 // If this is a redeclaration, check that the type we just deduced matches
6204 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00006205 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00006206 MergeVarDeclTypes(VDecl, Old);
6207 }
Richard Smith01888722011-12-15 19:20:59 +00006208
6209 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6210 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6211 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6212 VDecl->setInvalidDecl();
6213 return;
6214 }
6215
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006216 if (!VDecl->getType()->isDependentType()) {
6217 // A definition must end up with a complete type, which means it must be
6218 // complete with the restriction that an array type might be completed by
6219 // the initializer; note that later code assumes this restriction.
6220 QualType BaseDeclType = VDecl->getType();
6221 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6222 BaseDeclType = Array->getElementType();
6223 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6224 diag::err_typecheck_decl_incomplete_type)) {
6225 RealDecl->setInvalidDecl();
6226 return;
6227 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006228
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006229 // The variable can not have an abstract class type.
6230 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6231 diag::err_abstract_type_in_decl,
6232 AbstractVariableType))
6233 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00006234 }
6235
Sebastian Redl31310a22010-02-01 20:16:42 +00006236 const VarDecl *Def;
6237 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006238 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00006239 << VDecl->getDeclName();
6240 Diag(Def->getLocation(), diag::note_previous_definition);
6241 VDecl->setInvalidDecl();
6242 return;
6243 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006244
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006245 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00006246 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00006247 // C++ [class.static.data]p4
6248 // If a static data member is of const integral or const
6249 // enumeration type, its declaration in the class definition can
6250 // specify a constant-initializer which shall be an integral
6251 // constant expression (5.19). In that case, the member can appear
6252 // in integral constant expressions. The member shall still be
6253 // defined in a namespace scope if it is used in the program and the
6254 // namespace scope definition shall not contain an initializer.
6255 //
6256 // We already performed a redefinition check above, but for static
6257 // data members we also need to check whether there was an in-class
6258 // declaration with an initializer.
6259 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00006260 Diag(VDecl->getLocation(), diag::err_redefinition)
6261 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00006262 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6263 return;
6264 }
Douglas Gregor275a3692009-03-10 23:43:53 +00006265
Douglas Gregora31040f2010-12-16 01:31:22 +00006266 if (VDecl->hasLocalStorage())
6267 getCurFunction()->setHasBranchProtectedScope();
6268
6269 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6270 VDecl->setInvalidDecl();
6271 return;
6272 }
6273 }
John McCalle46f62c2010-08-01 01:24:59 +00006274
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00006275 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6276 // a kernel function cannot be initialized."
6277 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6278 Diag(VDecl->getLocation(), diag::err_local_cant_init);
6279 VDecl->setInvalidDecl();
6280 return;
6281 }
6282
Steve Naroffbb204692007-09-12 14:07:44 +00006283 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00006284 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00006285 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00006286
6287 // Top-level message sends default to 'id' when we're in a debugger
6288 // and we are assigning it to a variable of 'id' type.
David Blaikie4e4d0842012-03-11 07:00:24 +00006289 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00006290 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6291 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6292 if (Result.isInvalid()) {
6293 VDecl->setInvalidDecl();
6294 return;
6295 }
6296 Init = Result.take();
6297 }
Richard Smith01888722011-12-15 19:20:59 +00006298
6299 // Perform the initialization.
6300 if (!VDecl->isInvalidDecl()) {
6301 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6302 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00006303 = DirectInit ?
6304 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6305 Init->getLocStart(),
6306 Init->getLocEnd())
6307 : InitializationKind::CreateDirectList(
6308 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00006309 : InitializationKind::CreateCopy(VDecl->getLocation(),
6310 Init->getLocStart());
6311
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006312 Expr **Args = &Init;
6313 unsigned NumArgs = 1;
6314 if (CXXDirectInit) {
6315 Args = CXXDirectInit->getExprs();
6316 NumArgs = CXXDirectInit->getNumExprs();
6317 }
6318 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
Richard Smith01888722011-12-15 19:20:59 +00006319 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006320 MultiExprArg(*this, Args,NumArgs),
Richard Smith01888722011-12-15 19:20:59 +00006321 &DclT);
6322 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00006323 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00006324 return;
Steve Naroffbb204692007-09-12 14:07:44 +00006325 }
Richard Smith01888722011-12-15 19:20:59 +00006326
6327 Init = Result.takeAs<Expr>();
6328 }
6329
6330 // If the type changed, it means we had an incomplete type that was
6331 // completed by the initializer. For example:
6332 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00006333 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00006334 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00006335 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00006336
6337 // Check any implicit conversions within the expression.
6338 CheckImplicitConversions(Init, VDecl->getLocation());
6339
6340 if (!VDecl->isInvalidDecl())
6341 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6342
6343 Init = MaybeCreateExprWithCleanups(Init);
6344 // Attach the initializer to the decl.
6345 VDecl->setInit(Init);
6346
6347 if (VDecl->isLocalVarDecl()) {
6348 // C99 6.7.8p4: All the expressions in an initializer for an object that has
6349 // static storage duration shall be constant expressions or string literals.
6350 // C++ does not have this restriction.
David Blaikie4e4d0842012-03-11 07:00:24 +00006351 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
Richard Smith01888722011-12-15 19:20:59 +00006352 VDecl->getStorageClass() == SC_Static)
6353 CheckForConstantInitializer(Init, DclT);
Mike Stump1eb44332009-09-09 15:08:12 +00006354 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00006355 VDecl->getLexicalDeclContext()->isRecord()) {
6356 // This is an in-class initialization for a static data member, e.g.,
6357 //
6358 // struct S {
6359 // static const int value = 17;
6360 // };
6361
Douglas Gregor021c3b32009-03-11 23:00:04 +00006362 // C++ [class.mem]p4:
6363 // A member-declarator can contain a constant-initializer only
6364 // if it declares a static member (9.4) of const integral or
6365 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00006366 //
Richard Smith01888722011-12-15 19:20:59 +00006367 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00006368 // If a non-volatile const static data member is of integral or
6369 // enumeration type, its declaration in the class definition can
6370 // specify a brace-or-equal-initializer in which every initalizer-clause
6371 // that is an assignment-expression is a constant expression. A static
6372 // data member of literal type can be declared in the class definition
6373 // with the constexpr specifier; if so, its declaration shall specify a
6374 // brace-or-equal-initializer in which every initializer-clause that is
6375 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00006376
6377 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00006378 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00006379
Richard Smithc6d990a2011-09-29 19:11:37 +00006380 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00006381 // type. We separately check that every constexpr variable is of literal
6382 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00006383 } else if (VDecl->isConstexpr()) {
6384
John McCall4e635642010-09-10 23:21:22 +00006385 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00006386 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00006387 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6388 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00006389 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00006390
6391 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00006392 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00006393 // Check whether the expression is a constant expression.
6394 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00006395 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00006396 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00006397 // in-class initializer cannot be volatile.
6398 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6399 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00006400 ; // Nothing to check.
6401 else if (Init->isIntegerConstantExpr(Context, &Loc))
6402 ; // Ok, it's an ICE!
6403 else if (Init->isEvaluatable(Context)) {
6404 // If we can constant fold the initializer through heroics, accept it,
6405 // but report this as a use of an extension for -pedantic.
6406 Diag(Loc, diag::ext_in_class_initializer_non_constant)
6407 << Init->getSourceRange();
6408 } else {
6409 // Otherwise, this is some crazy unknown case. Report the issue at the
6410 // location provided by the isIntegerConstantExpr failed check.
6411 Diag(Loc, diag::err_in_class_initializer_non_constant)
6412 << Init->getSourceRange();
6413 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00006414 }
6415
Richard Smith01888722011-12-15 19:20:59 +00006416 // We allow foldable floating-point constants as an extension.
6417 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithc6d990a2011-09-29 19:11:37 +00006418 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
Richard Smith01888722011-12-15 19:20:59 +00006419 << DclT << Init->getSourceRange();
David Blaikie4e4d0842012-03-11 07:00:24 +00006420 if (getLangOpts().CPlusPlus0x)
Richard Smith2d23ec22011-09-30 00:33:19 +00006421 Diag(VDecl->getLocation(),
6422 diag::note_in_class_initializer_float_type_constexpr)
6423 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
John McCall4e635642010-09-10 23:21:22 +00006424
Richard Smith01888722011-12-15 19:20:59 +00006425 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
John McCall4e635642010-09-10 23:21:22 +00006426 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6427 << Init->getSourceRange();
6428 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00006429 }
Richard Smith947be192011-09-29 23:18:34 +00006430
Richard Smith01888722011-12-15 19:20:59 +00006431 // Suggest adding 'constexpr' in C++11 for literal types.
David Blaikie4e4d0842012-03-11 07:00:24 +00006432 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
Richard Smith947be192011-09-29 23:18:34 +00006433 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00006434 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00006435 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6436 VDecl->setConstexpr(true);
6437
Richard Smithc6d990a2011-09-29 19:11:37 +00006438 } else {
6439 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00006440 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00006441 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00006442 }
Steve Naroff248a7532008-04-15 22:42:06 +00006443 } else if (VDecl->isFileVarDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00006444 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006445 (!getLangOpts().CPlusPlus ||
Douglas Gregor66dd9392010-04-22 14:36:26 +00006446 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff410e3e22007-09-12 20:13:48 +00006447 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00006448
Richard Smith01888722011-12-15 19:20:59 +00006449 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00006450 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00006451 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00006452 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00006453
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006454 // We will represent direct-initialization similarly to copy-initialization:
6455 // int x(1); -as-> int x = 1;
6456 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6457 //
6458 // Clients that want to distinguish between the two forms, can check for
6459 // direct initializer using VarDecl::getInitStyle().
6460 // A major benefit is that clients that don't particularly care about which
6461 // exactly form was it (like the CodeGen) can handle both cases without
6462 // special case code.
6463
6464 // C++ 8.5p11:
6465 // The form of initialization (using parentheses or '=') is generally
6466 // insignificant, but does matter when the entity being initialized has a
6467 // class type.
6468 if (CXXDirectInit) {
6469 assert(DirectInit && "Call-style initializer must be direct init.");
6470 VDecl->setInitStyle(VarDecl::CallInit);
6471 } else if (DirectInit) {
6472 // This must be list-initialization. No other way is direct-initialization.
6473 VDecl->setInitStyle(VarDecl::ListInit);
6474 }
6475
John McCall2998d6b2011-01-19 11:48:09 +00006476 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00006477}
6478
John McCall7727acf2010-03-31 02:13:20 +00006479/// ActOnInitializerError - Given that there was an error parsing an
6480/// initializer for the given declaration, try to return to some form
6481/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00006482void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00006483 // Our main concern here is re-establishing invariants like "a
6484 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00006485 if (!D || D->isInvalidDecl()) return;
6486
6487 VarDecl *VD = dyn_cast<VarDecl>(D);
6488 if (!VD) return;
6489
Richard Smith34b41d92011-02-20 03:19:35 +00006490 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00006491 if (ParsingInitForAutoVars.count(D)) {
6492 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00006493 return;
6494 }
6495
John McCall7727acf2010-03-31 02:13:20 +00006496 QualType Ty = VD->getType();
6497 if (Ty->isDependentType()) return;
6498
6499 // Require a complete type.
6500 if (RequireCompleteType(VD->getLocation(),
6501 Context.getBaseElementType(Ty),
6502 diag::err_typecheck_decl_incomplete_type)) {
6503 VD->setInvalidDecl();
6504 return;
6505 }
6506
6507 // Require an abstract type.
6508 if (RequireNonAbstractType(VD->getLocation(), Ty,
6509 diag::err_abstract_type_in_decl,
6510 AbstractVariableType)) {
6511 VD->setInvalidDecl();
6512 return;
6513 }
6514
6515 // Don't bother complaining about constructors or destructors,
6516 // though.
6517}
6518
John McCalld226f652010-08-21 09:40:31 +00006519void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00006520 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00006521 // If there is no declaration, there was an error parsing it. Just ignore it.
6522 if (RealDecl == 0)
6523 return;
6524
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006525 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6526 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00006527
Richard Smithdd4b3502011-12-25 21:17:58 +00006528 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00006529 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00006530 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6531 << Var->getDeclName() << Type;
6532 Var->setInvalidDecl();
6533 return;
6534 }
Mike Stump1eb44332009-09-09 15:08:12 +00006535
Richard Smithdd4b3502011-12-25 21:17:58 +00006536 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00006537 // the constexpr specifier; if so, its declaration shall specify
6538 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00006539 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6540 // the definition of a variable [...] or the declaration of a static data
6541 // member.
6542 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6543 if (Var->isStaticDataMember())
6544 Diag(Var->getLocation(),
6545 diag::err_constexpr_static_mem_var_requires_init)
6546 << Var->getDeclName();
6547 else
6548 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00006549 Var->setInvalidDecl();
6550 return;
6551 }
6552
Douglas Gregor60c93c92010-02-09 07:26:29 +00006553 switch (Var->isThisDeclarationADefinition()) {
6554 case VarDecl::Definition:
6555 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6556 break;
6557
6558 // We have an out-of-line definition of a static data member
6559 // that has an in-class initializer, so we type-check this like
6560 // a declaration.
6561 //
6562 // Fall through
6563
6564 case VarDecl::DeclarationOnly:
6565 // It's only a declaration.
6566
6567 // Block scope. C99 6.7p7: If an identifier for an object is
6568 // declared with no linkage (C99 6.2.2p6), the type for the
6569 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00006570 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00006571 !Var->getLinkage() && !Var->isInvalidDecl() &&
6572 RequireCompleteType(Var->getLocation(), Type,
6573 diag::err_typecheck_decl_incomplete_type))
6574 Var->setInvalidDecl();
6575
6576 // Make sure that the type is not abstract.
6577 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6578 RequireNonAbstractType(Var->getLocation(), Type,
6579 diag::err_abstract_type_in_decl,
6580 AbstractVariableType))
6581 Var->setInvalidDecl();
6582 return;
6583
6584 case VarDecl::TentativeDefinition:
6585 // File scope. C99 6.9.2p2: A declaration of an identifier for an
6586 // object that has file scope without an initializer, and without a
6587 // storage-class specifier or with the storage-class specifier "static",
6588 // constitutes a tentative definition. Note: A tentative definition with
6589 // external linkage is valid (C99 6.2.2p5).
6590 if (!Var->isInvalidDecl()) {
6591 if (const IncompleteArrayType *ArrayT
6592 = Context.getAsIncompleteArrayType(Type)) {
6593 if (RequireCompleteType(Var->getLocation(),
6594 ArrayT->getElementType(),
6595 diag::err_illegal_decl_array_incomplete_type))
6596 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00006597 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00006598 // C99 6.9.2p3: If the declaration of an identifier for an object is
6599 // a tentative definition and has internal linkage (C99 6.2.2p3), the
6600 // declared type shall not be an incomplete type.
6601 // NOTE: code such as the following
6602 // static struct s;
6603 // struct s { int a; };
6604 // is accepted by gcc. Hence here we issue a warning instead of
6605 // an error and we do not invalidate the static declaration.
6606 // NOTE: to avoid multiple warnings, only check the first declaration.
Douglas Gregoref96ee02012-01-14 16:38:05 +00006607 if (Var->getPreviousDecl() == 0)
Douglas Gregor60c93c92010-02-09 07:26:29 +00006608 RequireCompleteType(Var->getLocation(), Type,
6609 diag::ext_typecheck_decl_incomplete_type);
6610 }
6611 }
6612
6613 // Record the tentative definition; we're done.
6614 if (!Var->isInvalidDecl())
6615 TentativeDefinitions.push_back(Var);
6616 return;
6617 }
6618
6619 // Provide a specific diagnostic for uninitialized variable
6620 // definitions with incomplete array type.
6621 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00006622 Diag(Var->getLocation(),
6623 diag::err_typecheck_incomplete_array_needs_initializer);
6624 Var->setInvalidDecl();
6625 return;
6626 }
6627
John McCallb567a8b2010-08-01 01:25:24 +00006628 // Provide a specific diagnostic for uninitialized variable
6629 // definitions with reference type.
6630 if (Type->isReferenceType()) {
6631 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6632 << Var->getDeclName()
6633 << SourceRange(Var->getLocation(), Var->getLocation());
6634 Var->setInvalidDecl();
6635 return;
6636 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00006637
6638 // Do not attempt to type-check the default initializer for a
6639 // variable with dependent type.
6640 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00006641 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00006642
Douglas Gregor60c93c92010-02-09 07:26:29 +00006643 if (Var->isInvalidDecl())
6644 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00006645
Douglas Gregor60c93c92010-02-09 07:26:29 +00006646 if (RequireCompleteType(Var->getLocation(),
6647 Context.getBaseElementType(Type),
6648 diag::err_typecheck_decl_incomplete_type)) {
6649 Var->setInvalidDecl();
6650 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006651 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006652
Douglas Gregor60c93c92010-02-09 07:26:29 +00006653 // The variable can not have an abstract class type.
6654 if (RequireNonAbstractType(Var->getLocation(), Type,
6655 diag::err_abstract_type_in_decl,
6656 AbstractVariableType)) {
6657 Var->setInvalidDecl();
6658 return;
6659 }
6660
Douglas Gregor4337dc72011-05-21 17:52:48 +00006661 // Check for jumps past the implicit initializer. C++0x
6662 // clarifies that this applies to a "variable with automatic
6663 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00006664 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00006665 // A program that jumps from a point where a variable with automatic
6666 // storage duration is not in scope to a point where it is in scope is
6667 // ill-formed unless the variable has scalar type, class type with a
6668 // trivial default constructor and a trivial destructor, a cv-qualified
6669 // version of one of these types, or an array of one of the preceding
6670 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00006671 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00006672 if (const RecordType *Record
6673 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00006674 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00006675 // Mark the function for further checking even if the looser rules of
6676 // C++11 do not require such checks, so that we can diagnose
6677 // incompatibilities with C++98.
6678 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00006679 getCurFunction()->setHasBranchProtectedScope();
6680 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00006681 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00006682
6683 // C++03 [dcl.init]p9:
6684 // If no initializer is specified for an object, and the
6685 // object is of (possibly cv-qualified) non-POD class type (or
6686 // array thereof), the object shall be default-initialized; if
6687 // the object is of const-qualified type, the underlying class
6688 // type shall have a user-declared default
6689 // constructor. Otherwise, if no initializer is specified for
6690 // a non- static object, the object and its subobjects, if
6691 // any, have an indeterminate initial value); if the object
6692 // or any of its subobjects are of const-qualified type, the
6693 // program is ill-formed.
6694 // C++0x [dcl.init]p11:
6695 // If no initializer is specified for an object, the object is
6696 // default-initialized; [...].
6697 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6698 InitializationKind Kind
6699 = InitializationKind::CreateDefault(Var->getLocation());
6700
6701 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6702 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6703 MultiExprArg(*this, 0, 0));
6704 if (Init.isInvalid())
6705 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006706 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00006707 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00006708 // This is important for template substitution.
6709 Var->setInitStyle(VarDecl::CallInit);
6710 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00006711
John McCall2998d6b2011-01-19 11:48:09 +00006712 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006713 }
6714}
6715
Richard Smithad762fc2011-04-14 22:09:26 +00006716void Sema::ActOnCXXForRangeDecl(Decl *D) {
6717 VarDecl *VD = dyn_cast<VarDecl>(D);
6718 if (!VD) {
6719 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6720 D->setInvalidDecl();
6721 return;
6722 }
6723
6724 VD->setCXXForRangeDecl(true);
6725
6726 // for-range-declaration cannot be given a storage class specifier.
6727 int Error = -1;
6728 switch (VD->getStorageClassAsWritten()) {
6729 case SC_None:
6730 break;
6731 case SC_Extern:
6732 Error = 0;
6733 break;
6734 case SC_Static:
6735 Error = 1;
6736 break;
6737 case SC_PrivateExtern:
6738 Error = 2;
6739 break;
6740 case SC_Auto:
6741 Error = 3;
6742 break;
6743 case SC_Register:
6744 Error = 4;
6745 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00006746 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00006747 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00006748 }
Richard Smithc6d990a2011-09-29 19:11:37 +00006749 if (VD->isConstexpr())
6750 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00006751 if (Error != -1) {
6752 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6753 << VD->getDeclName() << Error;
6754 D->setInvalidDecl();
6755 }
6756}
6757
John McCall2998d6b2011-01-19 11:48:09 +00006758void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6759 if (var->isInvalidDecl()) return;
6760
John McCallf85e1932011-06-15 23:02:42 +00006761 // In ARC, don't allow jumps past the implicit initialization of a
6762 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00006763 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00006764 var->hasLocalStorage()) {
6765 switch (var->getType().getObjCLifetime()) {
6766 case Qualifiers::OCL_None:
6767 case Qualifiers::OCL_ExplicitNone:
6768 case Qualifiers::OCL_Autoreleasing:
6769 break;
6770
6771 case Qualifiers::OCL_Weak:
6772 case Qualifiers::OCL_Strong:
6773 getCurFunction()->setHasBranchProtectedScope();
6774 break;
6775 }
6776 }
6777
John McCall2998d6b2011-01-19 11:48:09 +00006778 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00006779 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00006780
6781 QualType baseType = Context.getBaseElementType(var->getType());
6782 if (baseType->isDependentType()) return;
6783
6784 // __block variables might require us to capture a copy-initializer.
6785 if (var->hasAttr<BlocksAttr>()) {
6786 // It's currently invalid to ever have a __block variable with an
6787 // array type; should we diagnose that here?
6788
6789 // Regardless, we don't want to ignore array nesting when
6790 // constructing this copy.
6791 QualType type = var->getType();
6792
6793 if (type->isStructureOrClassType()) {
6794 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00006795 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
John McCall2998d6b2011-01-19 11:48:09 +00006796 ExprResult result =
6797 PerformCopyInitialization(
6798 InitializedEntity::InitializeBlock(poi, type, false),
6799 poi, Owned(varRef));
6800 if (!result.isInvalid()) {
6801 result = MaybeCreateExprWithCleanups(result);
6802 Expr *init = result.takeAs<Expr>();
6803 Context.setBlockVarCopyInits(var, init);
6804 }
6805 }
6806 }
6807
Richard Smith66f85712011-11-07 22:16:17 +00006808 Expr *Init = var->getInit();
6809 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6810
Richard Smith099e7f62011-12-19 06:19:21 +00006811 if (!var->getDeclContext()->isDependentContext() && Init) {
6812 if (IsGlobal && !var->isConstexpr() &&
6813 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6814 var->getLocation())
6815 != DiagnosticsEngine::Ignored &&
6816 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
Richard Smith66f85712011-11-07 22:16:17 +00006817 Diag(var->getLocation(), diag::warn_global_constructor)
6818 << Init->getSourceRange();
Richard Smith099e7f62011-12-19 06:19:21 +00006819
Richard Smith099e7f62011-12-19 06:19:21 +00006820 if (var->isConstexpr()) {
6821 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6822 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6823 SourceLocation DiagLoc = var->getLocation();
6824 // If the note doesn't add any useful information other than a source
6825 // location, fold it into the primary diagnostic.
6826 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6827 diag::note_invalid_subexpr_in_const_expr) {
6828 DiagLoc = Notes[0].first;
6829 Notes.clear();
6830 }
6831 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6832 << var << Init->getSourceRange();
6833 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6834 Diag(Notes[I].first, Notes[I].second);
6835 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00006836 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00006837 // Check whether the initializer of a const variable of integral or
6838 // enumeration type is an ICE now, since we can't tell whether it was
6839 // initialized by a constant expression if we check later.
6840 var->checkInitIsICE();
6841 }
Richard Smith66f85712011-11-07 22:16:17 +00006842 }
John McCall2998d6b2011-01-19 11:48:09 +00006843
6844 // Require the destructor.
6845 if (const RecordType *recordType = baseType->getAs<RecordType>())
6846 FinalizeVarWithDestructor(var, recordType);
6847}
6848
Richard Smith483b9f32011-02-21 20:05:19 +00006849/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6850/// any semantic actions necessary after any initializer has been attached.
6851void
6852Sema::FinalizeDeclaration(Decl *ThisDecl) {
6853 // Note that we are no longer parsing the initializer for this declaration.
6854 ParsingInitForAutoVars.erase(ThisDecl);
6855}
6856
John McCallb3d87482010-08-24 05:47:05 +00006857Sema::DeclGroupPtrTy
6858Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6859 Decl **Group, unsigned NumDecls) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006860 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00006861
6862 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00006863 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00006864
Richard Smith406c38e2011-02-23 00:37:57 +00006865 for (unsigned i = 0; i != NumDecls; ++i)
6866 if (Decl *D = Group[i])
6867 Decls.push_back(D);
6868
Chandler Carrutha7689ef2011-03-27 09:46:56 +00006869 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith406c38e2011-02-23 00:37:57 +00006870 DS.getTypeSpecType() == DeclSpec::TST_auto);
6871}
6872
6873/// BuildDeclaratorGroup - convert a list of declarations into a declaration
6874/// group, performing any necessary semantic checking.
6875Sema::DeclGroupPtrTy
6876Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6877 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00006878 // C++0x [dcl.spec.auto]p7:
6879 // If the type deduced for the template parameter U is not the same in each
6880 // deduction, the program is ill-formed.
6881 // FIXME: When initializer-list support is added, a distinction is needed
6882 // between the deduced type U and the deduced type which 'auto' stands for.
6883 // auto a = 0, b = { 1, 2, 3 };
6884 // is legal because the deduced type U is 'int' in both cases.
Richard Smith406c38e2011-02-23 00:37:57 +00006885 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00006886 QualType Deduced;
6887 CanQualType DeducedCanon;
6888 VarDecl *DeducedDecl = 0;
6889 for (unsigned i = 0; i != NumDecls; ++i) {
6890 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6891 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00006892 // Don't reissue diagnostics when instantiating a template.
6893 if (AT && D->isInvalidDecl())
6894 break;
Richard Smith34b41d92011-02-20 03:19:35 +00006895 if (AT && AT->isDeduced()) {
6896 QualType U = AT->getDeducedType();
6897 CanQualType UCanon = Context.getCanonicalType(U);
6898 if (Deduced.isNull()) {
6899 Deduced = U;
6900 DeducedCanon = UCanon;
6901 DeducedDecl = D;
6902 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00006903 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6904 diag::err_auto_different_deductions)
Richard Smith34b41d92011-02-20 03:19:35 +00006905 << Deduced << DeducedDecl->getDeclName()
6906 << U << D->getDeclName()
6907 << DeducedDecl->getInit()->getSourceRange()
6908 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00006909 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00006910 break;
6911 }
6912 }
6913 }
6914 }
6915 }
6916
Richard Smith406c38e2011-02-23 00:37:57 +00006917 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Reid Spencer5f016e22007-07-11 17:01:13 +00006918}
Steve Naroffe1223f72007-08-28 03:03:08 +00006919
Chris Lattner682bf922009-03-29 16:50:03 +00006920
Chris Lattner04421082008-04-08 04:40:51 +00006921/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6922/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00006923Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00006924 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00006925
Chris Lattner04421082008-04-08 04:40:51 +00006926 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00006927 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00006928 VarDecl::StorageClass StorageClass = SC_None;
6929 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00006930 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00006931 StorageClass = SC_Register;
6932 StorageClassAsWritten = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00006933 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00006934 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6935 StorageClass = SC_Auto;
6936 StorageClassAsWritten = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00006937 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00006938 Diag(DS.getStorageClassSpecLoc(),
6939 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00006940 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00006941 }
Eli Friedman63054b32009-04-19 20:27:55 +00006942
6943 if (D.getDeclSpec().isThreadSpecified())
6944 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006945 if (D.getDeclSpec().isConstexprSpecified())
6946 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6947 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00006948
Eli Friedman85a53192009-04-07 19:37:57 +00006949 DiagnoseFunctionSpecifiers(D);
6950
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00006951 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00006952 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00006953
David Blaikie4e4d0842012-03-11 07:00:24 +00006954 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00006955 // Check that there are no default arguments inside the type of this
6956 // parameter.
6957 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00006958
6959 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6960 if (D.getCXXScopeSpec().isSet()) {
6961 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6962 << D.getCXXScopeSpec().getRange();
6963 D.getCXXScopeSpec().clear();
6964 }
Douglas Gregor402abb52009-05-28 23:31:59 +00006965 }
6966
Sean Hunt7533a5b2010-11-03 01:07:06 +00006967 // Ensure we have a valid name
6968 IdentifierInfo *II = 0;
6969 if (D.hasName()) {
6970 II = D.getIdentifier();
6971 if (!II) {
6972 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6973 << GetNameForDeclarator(D).getName().getAsString();
6974 D.setInvalidType(true);
6975 }
6976 }
6977
Chris Lattnerd84aac12010-02-22 00:40:25 +00006978 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00006979 if (II) {
John McCall10f28732010-03-18 06:42:38 +00006980 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6981 ForRedeclaration);
6982 LookupName(R, S);
6983 if (R.isSingleResult()) {
6984 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00006985 if (PrevDecl->isTemplateParameter()) {
6986 // Maybe we will complain about the shadowed template parameter.
6987 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6988 // Just pretend that we didn't see the previous declaration.
6989 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00006990 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00006991 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00006992 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00006993
Chris Lattnercf79b012009-01-21 02:38:50 +00006994 // Recover by removing the name
6995 II = 0;
6996 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00006997 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00006998 }
Chris Lattner04421082008-04-08 04:40:51 +00006999 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007000 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00007001
John McCall7a9813c2010-01-22 00:28:27 +00007002 // Temporarily put parameter variables in the translation unit, not
7003 // the enclosing context. This prevents them from accidentally
7004 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00007005 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00007006 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007007 D.getIdentifierLoc(), II,
7008 parmDeclType, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00007009 StorageClass, StorageClassAsWritten);
Mike Stump1eb44332009-09-09 15:08:12 +00007010
Chris Lattnereaaebc72009-04-25 08:06:05 +00007011 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00007012 New->setInvalidDecl();
7013
7014 assert(S->isFunctionPrototypeScope());
7015 assert(S->getFunctionPrototypeDepth() >= 1);
7016 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7017 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00007018
Douglas Gregor44b43212008-12-11 16:49:14 +00007019 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00007020 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00007021 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00007022 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00007023
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007024 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00007025
Douglas Gregore3895852011-09-12 18:37:38 +00007026 if (D.getDeclSpec().isModulePrivateSpecified())
7027 Diag(New->getLocation(), diag::err_module_private_local)
7028 << 1 << New->getDeclName()
7029 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7030 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7031
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00007032 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00007033 Diag(New->getLocation(), diag::err_block_on_nonlocal);
7034 }
John McCalld226f652010-08-21 09:40:31 +00007035 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00007036}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00007037
John McCall82dc0092010-06-04 11:21:44 +00007038/// \brief Synthesizes a variable for a parameter arising from a
7039/// typedef.
7040ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7041 SourceLocation Loc,
7042 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007043 /* FIXME: setting StartLoc == Loc.
7044 Would it be worth to modify callers so as to provide proper source
7045 location for the unnamed parameters, embedding the parameter's type? */
7046 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00007047 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCalld931b082010-08-26 03:08:43 +00007048 SC_None, SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00007049 Param->setImplicit();
7050 return Param;
7051}
7052
John McCallfbce0e12010-08-24 09:05:15 +00007053void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7054 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00007055 // Don't diagnose unused-parameter errors in template instantiations; we
7056 // will already have done so in the template itself.
7057 if (!ActiveTemplateInstantiations.empty())
7058 return;
7059
7060 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00007061 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00007062 !(*Param)->hasAttr<UnusedAttr>()) {
7063 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7064 << (*Param)->getDeclName();
7065 }
7066 }
7067}
7068
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007069void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7070 ParmVarDecl * const *ParamEnd,
7071 QualType ReturnTy,
7072 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00007073 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007074 return;
7075
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00007076 // Warn if the return value is pass-by-value and larger than the specified
7077 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00007078 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007079 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00007080 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007081 Diag(D->getLocation(), diag::warn_return_value_size)
7082 << D->getDeclName() << Size;
7083 }
7084
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00007085 // Warn if any parameter is pass-by-value and larger than the specified
7086 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007087 for (; Param != ParamEnd; ++Param) {
7088 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00007089 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007090 continue;
7091 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00007092 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007093 Diag((*Param)->getLocation(), diag::warn_parameter_size)
7094 << (*Param)->getDeclName() << Size;
7095 }
7096}
7097
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007098ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7099 SourceLocation NameLoc, IdentifierInfo *Name,
7100 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00007101 VarDecl::StorageClass StorageClass,
7102 VarDecl::StorageClass StorageClassAsWritten) {
John McCallf85e1932011-06-15 23:02:42 +00007103 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00007104 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00007105 T.getObjCLifetime() == Qualifiers::OCL_None &&
7106 T->isObjCLifetimeType()) {
7107
7108 Qualifiers::ObjCLifetime lifetime;
7109
7110 // Special cases for arrays:
7111 // - if it's const, use __unsafe_unretained
7112 // - otherwise, it's an error
7113 if (T->isArrayType()) {
7114 if (!T.isConstQualified()) {
Fariborz Jahanian175fb102011-10-03 22:11:57 +00007115 DelayedDiagnostics.add(
7116 sema::DelayedDiagnostic::makeForbiddenType(
7117 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
John McCallf85e1932011-06-15 23:02:42 +00007118 }
7119 lifetime = Qualifiers::OCL_ExplicitNone;
7120 } else {
7121 lifetime = T->getObjCARCImplicitLifetime();
7122 }
7123 T = Context.getLifetimeQualifiedType(T, lifetime);
7124 }
7125
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007126 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00007127 Context.getAdjustedParameterType(T),
7128 TSInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00007129 StorageClass, StorageClassAsWritten,
7130 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00007131
7132 // Parameters can not be abstract class types.
7133 // For record types, this is done by the AbstractClassUsageDiagnoser once
7134 // the class has been completely parsed.
7135 if (!CurContext->isRecord() &&
7136 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7137 AbstractParamType))
7138 New->setInvalidDecl();
7139
7140 // Parameter declarators cannot be interface types. All ObjC objects are
7141 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00007142 if (T->isObjCObjectType()) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00007143 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00007144 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7145 << FixItHint::CreateInsertion(NameLoc, "*");
7146 T = Context.getObjCObjectPointerType(T);
7147 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00007148 }
7149
7150 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7151 // duration shall not be qualified by an address-space qualifier."
7152 // Since all parameters have automatic store duration, they can not have
7153 // an address space.
7154 if (T.getAddressSpace() != 0) {
7155 Diag(NameLoc, diag::err_arg_with_address_space);
7156 New->setInvalidDecl();
7157 }
7158
7159 return New;
7160}
7161
Douglas Gregora3a83512009-04-01 23:51:29 +00007162void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7163 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00007164 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00007165
Reid Spencer5f016e22007-07-11 17:01:13 +00007166 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7167 // for a K&R function.
7168 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00007169 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7170 --i;
Chris Lattner04421082008-04-08 04:40:51 +00007171 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007172 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00007173 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00007174 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00007175 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00007176 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00007177 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00007178 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00007179
Reid Spencer5f016e22007-07-11 17:01:13 +00007180 // Implicitly declare the argument as type 'int' for lack of a better
7181 // type.
John McCall0b7e6782011-03-24 11:26:52 +00007182 AttributeFactory attrs;
7183 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00007184 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00007185 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00007186 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00007187 PrevSpec, DiagID);
Chris Lattner04421082008-04-08 04:40:51 +00007188 Declarator ParamD(DS, Declarator::KNRTypeListContext);
7189 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00007190 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00007191 }
7192 }
Mike Stump1eb44332009-09-09 15:08:12 +00007193 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00007194}
7195
Richard Smith87162c22012-04-17 22:30:01 +00007196Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00007197 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00007198 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00007199 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00007200
Douglas Gregor45fa5602011-11-07 20:56:01 +00007201 D.setFunctionDefinitionKind(FDK_Definition);
John McCalld226f652010-08-21 09:40:31 +00007202 Decl *DP = HandleDeclarator(ParentScope, D,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007203 MultiTemplateParamsArg(*this));
Chris Lattner682bf922009-03-29 16:50:03 +00007204 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00007205}
7206
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007207static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7208 // Don't warn about invalid declarations.
7209 if (FD->isInvalidDecl())
7210 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00007211
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007212 // Or declarations that aren't global.
7213 if (!FD->isGlobal())
7214 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00007215
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007216 // Don't warn about C++ member functions.
7217 if (isa<CXXMethodDecl>(FD))
7218 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00007219
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007220 // Don't warn about 'main'.
7221 if (FD->isMain())
7222 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00007223
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007224 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00007225 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007226 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00007227
7228 // Don't warn about function templates.
7229 if (FD->getDescribedFunctionTemplate())
7230 return false;
7231
7232 // Don't warn about function template specializations.
7233 if (FD->isFunctionTemplateSpecialization())
7234 return false;
7235
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007236 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00007237 for (const FunctionDecl *Prev = FD->getPreviousDecl();
7238 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007239 // Ignore any declarations that occur in function or method
7240 // scope, because they aren't visible from the header.
7241 if (Prev->getDeclContext()->isFunctionOrMethod())
7242 continue;
7243
7244 MissingPrototype = !Prev->getType()->isFunctionProtoType();
7245 break;
7246 }
7247
7248 return MissingPrototype;
7249}
7250
Francois Pichetd4a0caf2011-04-22 23:20:44 +00007251void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7252 // Don't complain if we're in GNU89 mode and the previous definition
7253 // was an extern inline function.
7254 const FunctionDecl *Definition;
Sean Hunt10620eb2011-05-06 20:44:56 +00007255 if (FD->isDefined(Definition) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007256 !canRedefineFunction(Definition, getLangOpts())) {
7257 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
Francois Pichetd4a0caf2011-04-22 23:20:44 +00007258 Definition->getStorageClass() == SC_Extern)
7259 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00007260 << FD->getDeclName() << getLangOpts().CPlusPlus;
Francois Pichetd4a0caf2011-04-22 23:20:44 +00007261 else
7262 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7263 Diag(Definition->getLocation(), diag::note_previous_definition);
7264 }
7265}
7266
John McCalld226f652010-08-21 09:40:31 +00007267Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00007268 // Clear the last template instantiation error context.
7269 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7270
Douglas Gregor52591bf2009-06-24 00:54:41 +00007271 if (!D)
7272 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00007273 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007274
John McCalld226f652010-08-21 09:40:31 +00007275 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00007276 FD = FunTmpl->getTemplatedDecl();
7277 else
John McCalld226f652010-08-21 09:40:31 +00007278 FD = cast<FunctionDecl>(D);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00007279
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007280 // Enter a new function scope
7281 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00007282
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00007283 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00007284 if (!FD->isLateTemplateParsed())
7285 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00007286
Douglas Gregorcda9c672009-02-16 17:45:42 +00007287 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00007288 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor655753a2009-02-17 16:03:01 +00007289 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00007290 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00007291 FD->setInvalidDecl();
7292 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00007293 }
7294
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00007295 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00007296 // (C99 6.9.1p3, C++ [dcl.fct]p6).
7297 QualType ResultType = FD->getResultType();
7298 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00007299 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00007300 RequireCompleteType(FD->getLocation(), ResultType,
7301 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00007302 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00007303
Douglas Gregor8499f3f2009-03-31 16:35:03 +00007304 // GNU warning -Wmissing-prototypes:
7305 // Warn if a global function is defined without a previous
7306 // prototype declaration. This warning is issued even if the
7307 // definition itself provides a prototype. The aim is to detect
7308 // global functions that fail to be declared in header files.
Anders Carlsson9f89dd72009-12-09 03:30:09 +00007309 if (ShouldWarnAboutMissingPrototype(FD))
7310 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregor8499f3f2009-03-31 16:35:03 +00007311
Douglas Gregore2c31ff2009-05-15 17:59:04 +00007312 if (FnBodyScope)
7313 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00007314
Chris Lattner04421082008-04-08 04:40:51 +00007315 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00007316 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7317 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00007318
7319 // Introduce our parameters into the function scope
7320 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7321 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00007322 Param->setOwningFunction(FD);
7323
Chris Lattner04421082008-04-08 04:40:51 +00007324 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00007325 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00007326 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00007327
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00007328 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00007329 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007330 }
Chris Lattner04421082008-04-08 04:40:51 +00007331
James Molloy16f1f712012-02-29 10:24:19 +00007332 // If we had any tags defined in the function prototype,
7333 // introduce them into the function scope.
7334 if (FnBodyScope) {
7335 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7336 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7337 NamedDecl *D = *I;
7338
7339 // Some of these decls (like enums) may have been pinned to the translation unit
7340 // for lack of a real context earlier. If so, remove from the translation unit
7341 // and reattach to the current context.
7342 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7343 // Is the decl actually in the context?
7344 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7345 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7346 if (*DI == D) {
7347 Context.getTranslationUnitDecl()->removeDecl(D);
7348 break;
7349 }
7350 }
7351 // Either way, reassign the lexical decl context to our FunctionDecl.
7352 D->setLexicalDeclContext(CurContext);
7353 }
7354
7355 // If the decl has a non-null name, make accessible in the current scope.
7356 if (!D->getName().empty())
7357 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7358
7359 // Similarly, dive into enums and fish their constants out, making them
7360 // accessible in this scope.
7361 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7362 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7363 EE = ED->enumerator_end(); EI != EE; ++EI)
7364 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7365 }
7366 }
7367 }
7368
Richard Smith87162c22012-04-17 22:30:01 +00007369 // Ensure that the function's exception specification is instantiated.
7370 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7371 ResolveExceptionSpec(D->getLocation(), FPT);
7372
Anton Korobeynikov2f402702008-12-26 00:52:02 +00007373 // Checking attributes of current function definition
7374 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00007375 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7376 if (DA && (!FD->getAttr<DLLExportAttr>())) {
7377 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00007378 // Microsoft accepts dllimport for functions defined within class scope.
7379 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00007380 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00007381 Diag(FD->getLocation(),
7382 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7383 << "dllimport";
7384 FD->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +00007385 return FD;
Ted Kremenek12911a82010-02-21 05:12:53 +00007386 }
7387
7388 // Visual C++ appears to not think this is an issue, so only issue
7389 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00007390 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00007391 // If a symbol previously declared dllimport is later defined, the
7392 // attribute is ignored in subsequent references, and a warning is
7393 // emitted.
7394 Diag(FD->getLocation(),
7395 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00007396 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00007397 }
7398 }
John McCalld226f652010-08-21 09:40:31 +00007399 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00007400}
7401
Douglas Gregor5077c382010-05-15 06:01:05 +00007402/// \brief Given the set of return statements within a function body,
7403/// compute the variables that are subject to the named return value
7404/// optimization.
7405///
7406/// Each of the variables that is subject to the named return value
7407/// optimization will be marked as NRVO variables in the AST, and any
7408/// return statement that has a marked NRVO variable as its NRVO candidate can
7409/// use the named return value optimization.
7410///
7411/// This function applies a very simplistic algorithm for NRVO: if every return
7412/// statement in the function has the same NRVO candidate, that candidate is
7413/// the NRVO variable.
7414///
7415/// FIXME: Employ a smarter algorithm that accounts for multiple return
7416/// statements and the lifetimes of the NRVO candidates. We should be able to
7417/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00007418void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00007419 ReturnStmt **Returns = Scope->Returns.data();
7420
Douglas Gregor5077c382010-05-15 06:01:05 +00007421 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00007422 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00007423 if (!Returns[I]->getNRVOCandidate())
7424 return;
7425
7426 if (!NRVOCandidate)
7427 NRVOCandidate = Returns[I]->getNRVOCandidate();
7428 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7429 return;
7430 }
7431
7432 if (NRVOCandidate)
7433 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7434}
7435
John McCallf312b1e2010-08-26 23:41:50 +00007436Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregore2c31ff2009-05-15 17:59:04 +00007437 return ActOnFinishFunctionBody(D, move(BodyArg), false);
7438}
7439
John McCall9ae2f072010-08-23 23:25:46 +00007440Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7441 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00007442 FunctionDecl *FD = 0;
7443 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7444 if (FunTmpl)
7445 FD = FunTmpl->getTemplatedDecl();
7446 else
7447 FD = dyn_cast_or_null<FunctionDecl>(dcl);
7448
Ted Kremenekd064fdc2010-03-23 00:13:23 +00007449 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00007450 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007451
Douglas Gregord83d0402009-08-22 00:34:47 +00007452 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00007453 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00007454
7455 // If the function implicitly returns zero (like 'main') or is naked,
7456 // don't complain about missing return statements.
7457 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00007458 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00007459
Francois Pichet6a247472011-05-11 02:14:46 +00007460 // MSVC permits the use of pure specifier (=0) on function definition,
7461 // defined at class scope, warn about this non standard construct.
David Blaikie4e4d0842012-03-11 07:00:24 +00007462 if (getLangOpts().MicrosoftExt && FD->isPure())
Francois Pichet6a247472011-05-11 02:14:46 +00007463 Diag(FD->getLocation(), diag::warn_pure_function_definition);
7464
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007465 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007466 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007467 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7468 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007469
7470 // If this is a constructor, we need a vtable.
7471 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7472 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00007473
Douglas Gregorf8b7f712011-09-06 20:46:03 +00007474 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007475 }
7476
Douglas Gregor76e3da52012-02-08 20:17:14 +00007477 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7478 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00007479 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00007480 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00007481 MD->setBody(Body);
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00007482 if (Body)
7483 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007484 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007485 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007486 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7487 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00007488
7489 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00007490 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00007491 }
Nico Weber9a1ecf02011-08-22 17:25:57 +00007492 if (ObjCShouldCallSuperDealloc) {
7493 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7494 ObjCShouldCallSuperDealloc = false;
7495 }
Nico Weber80cb6e62011-08-28 22:35:17 +00007496 if (ObjCShouldCallSuperFinalize) {
7497 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7498 ObjCShouldCallSuperFinalize = false;
7499 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00007500 } else {
John McCalld226f652010-08-21 09:40:31 +00007501 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00007502 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00007503
Nico Weber9a1ecf02011-08-22 17:25:57 +00007504 assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7505 "ObjC methods, which should have been handled in the block above.");
Nico Weber80cb6e62011-08-28 22:35:17 +00007506 assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7507 "ObjC methods, which should have been handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00007508
Reid Spencer5f016e22007-07-11 17:01:13 +00007509 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007510 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007511 // C++ constructors that have function-try-blocks can't have return
7512 // statements in the handlers of that block. (C++ [except.handle]p14)
7513 // Verify this.
7514 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7515 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7516
Richard Smith37bee672011-08-12 18:44:32 +00007517 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00007518 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00007519 !dcl->isInvalidDecl() &&
John McCallf85e1932011-06-15 23:02:42 +00007520 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007521 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00007522
John McCall15442822010-08-04 01:04:25 +00007523 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7524 if (!Destructor->getParent()->isDependentType())
7525 CheckDestructor(Destructor);
7526
John McCallef027fe2010-03-16 21:39:52 +00007527 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7528 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00007529 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007530
7531 // If any errors have occurred, clear out any temporaries that may have
7532 // been leftover. This ensures that these temporaries won't be picked up for
7533 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00007534 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00007535 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00007536 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00007537 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007538 // Since the body is valid, issue any analysis-based warnings that are
7539 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00007540 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007541 }
7542
Richard Smith86c3ae42012-02-13 03:54:03 +00007543 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7544 (!CheckConstexprFunctionDecl(FD) ||
7545 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00007546 FD->setInvalidDecl();
7547
John McCall80ee6e82011-11-10 05:35:25 +00007548 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00007549 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00007550 assert(MaybeODRUseExprs.empty() &&
7551 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007552 }
7553
John McCall90f97892010-03-25 22:08:03 +00007554 if (!IsInstantiation)
7555 PopDeclContext();
7556
Eli Friedmanec9ea722012-01-05 03:35:19 +00007557 PopFunctionScopeInfo(ActivePolicy, dcl);
Anders Carlssonf8a9a792009-11-13 19:21:49 +00007558
Douglas Gregord5b57282009-11-15 07:07:58 +00007559 // If any errors have occurred, clear out any temporaries that may have
7560 // been leftover. This ensures that these temporaries won't be picked up for
7561 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00007562 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00007563 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00007564 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00007565
John McCalld226f652010-08-21 09:40:31 +00007566 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00007567}
7568
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00007569
7570/// When we finish delayed parsing of an attribute, we must attach it to the
7571/// relevant Decl.
7572void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7573 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00007574 // Always attach attributes to the underlying decl.
7575 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7576 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007577 ProcessDeclAttributeList(S, D, Attrs.getList());
7578
7579 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
7580 if (Method->isStatic())
7581 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00007582}
7583
7584
Reid Spencer5f016e22007-07-11 17:01:13 +00007585/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7586/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00007587NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00007588 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00007589 // Before we produce a declaration for an implicitly defined
7590 // function, see whether there was a locally-scoped declaration of
7591 // this name as a function or variable. If so, use that
7592 // (non-visible) declaration, and complain about it.
7593 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorec12ce22011-07-28 14:20:37 +00007594 = findLocallyScopedExternalDecl(&II);
Douglas Gregor63935192009-03-02 00:19:53 +00007595 if (Pos != LocallyScopedExternalDecls.end()) {
7596 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7597 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7598 return Pos->second;
7599 }
7600
Chris Lattner37d10842008-05-05 21:18:06 +00007601 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007602 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00007603 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00007604 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00007605 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007606 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00007607 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007608 diag_id = diag::warn_implicit_function_decl;
7609 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00007610
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007611 // Because typo correction is expensive, only do it if the implicit
7612 // function declaration is going to be treated as an error.
7613 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7614 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00007615 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007616 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00007617 LookupOrdinaryName, S, 0, Validator))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007618 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7619 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00007620 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007621
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00007622 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7623 << FixItHint::CreateReplacement(Loc, CorrectedStr);
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007624
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00007625 if (Func->getLocation().isValid()
7626 && !II.getName().startswith("__builtin_"))
7627 Diag(Func->getLocation(), diag::note_previous_decl)
7628 << CorrectedQuotedStr;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00007629 }
Hans Wennborg122de3e2011-12-06 09:46:12 +00007630 }
7631
Reid Spencer5f016e22007-07-11 17:01:13 +00007632 // Set a Declarator for the implicit definition: int foo();
7633 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00007634 AttributeFactory attrFactory;
7635 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00007636 unsigned DiagID;
7637 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00007638 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00007639 assert(!Error && "Error setting up implicit decl!");
7640 Declarator D(DS, Declarator::BlockContext);
John McCall0b7e6782011-03-24 11:26:52 +00007641 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor83f51722011-01-26 03:43:54 +00007642 0, 0, true, SourceLocation(),
Douglas Gregor43f51032011-10-19 06:04:55 +00007643 SourceLocation(), SourceLocation(),
Douglas Gregor90ebed02011-07-13 21:47:47 +00007644 SourceLocation(),
Sebastian Redl6e5d3192011-03-05 22:42:13 +00007645 EST_None, SourceLocation(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +00007646 0, 0, 0, 0, 0, Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00007647 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00007648 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00007649 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00007650
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00007651 // Insert this function into translation-unit scope.
7652
7653 DeclContext *PrevDC = CurContext;
7654 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00007655
John McCalld226f652010-08-21 09:40:31 +00007656 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00007657 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00007658
7659 CurContext = PrevDC;
7660
Douglas Gregor3c385e52009-02-14 18:57:46 +00007661 AddKnownFunctionAttributes(FD);
7662
Steve Naroffe2ef8152008-04-04 14:32:09 +00007663 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00007664}
7665
Douglas Gregor3c385e52009-02-14 18:57:46 +00007666/// \brief Adds any function attributes that we know a priori based on
7667/// the declaration of this function.
7668///
7669/// These attributes can apply both to implicitly-declared builtins
7670/// (like __builtin___printf_chk) or to library-declared functions
7671/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00007672///
7673/// We need to check for duplicate attributes both here and where user-written
7674/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00007675void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7676 if (FD->isInvalidDecl())
7677 return;
7678
7679 // If this is a built-in function, map its builtin attributes to
7680 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00007681 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00007682 // Handle printf-formatting attributes.
7683 unsigned FormatIdx;
7684 bool HasVAListArg;
7685 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00007686 if (!FD->getAttr<FormatAttr>()) {
7687 const char *fmt = "printf";
7688 unsigned int NumParams = FD->getNumParams();
7689 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7690 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7691 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +00007692 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00007693 fmt, FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00007694 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00007695 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00007696 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00007697 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7698 HasVAListArg)) {
7699 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00007700 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7701 "scanf", FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00007702 HasVAListArg ? 0 : FormatIdx+2));
7703 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00007704
7705 // Mark const if we don't care about errno and that is the only
7706 // thing preventing the function from being const. This allows
7707 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +00007708 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00007709 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00007710 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00007711 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00007712 }
Mike Stump0feecbb2009-07-27 19:14:18 +00007713
Rafael Espindola67004152011-10-12 19:51:18 +00007714 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7715 !FD->getAttr<ReturnsTwiceAttr>())
7716 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00007717 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00007718 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00007719 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00007720 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +00007721 }
7722
7723 IdentifierInfo *Name = FD->getIdentifier();
7724 if (!Name)
7725 return;
David Blaikie4e4d0842012-03-11 07:00:24 +00007726 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00007727 FD->getDeclContext()->isTranslationUnit()) ||
7728 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00007729 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +00007730 LinkageSpecDecl::lang_c)) {
7731 // Okay: this could be a libc/libm/Objective-C function we know
7732 // about.
7733 } else
7734 return;
7735
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00007736 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00007737 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +00007738 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00007739 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00007740 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7741 "printf", 2,
Eli Friedmand7dad722009-06-10 04:01:38 +00007742 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +00007743 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00007744}
Reid Spencer5f016e22007-07-11 17:01:13 +00007745
John McCallba6a9bd2009-10-24 08:00:42 +00007746TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00007747 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007748 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00007749 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +00007750
John McCalla93c9342009-12-07 02:54:59 +00007751 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +00007752 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +00007753 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +00007754 }
7755
Reid Spencer5f016e22007-07-11 17:01:13 +00007756 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00007757 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +00007758 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +00007759 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00007760 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +00007761 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00007762
John McCallcde5a402011-02-01 08:20:08 +00007763 // Bail out immediately if we have an invalid declaration.
7764 if (D.isInvalidType()) {
7765 NewTD->setInvalidDecl();
7766 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +00007767 }
7768
Douglas Gregore3895852011-09-12 18:37:38 +00007769 if (D.getDeclSpec().isModulePrivateSpecified()) {
7770 if (CurContext->isFunctionOrMethod())
7771 Diag(NewTD->getLocation(), diag::err_module_private_local)
7772 << 2 << NewTD->getDeclName()
7773 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7774 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7775 else
7776 NewTD->setModulePrivate();
7777 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00007778
John McCallcde5a402011-02-01 08:20:08 +00007779 // C++ [dcl.typedef]p8:
7780 // If the typedef declaration defines an unnamed class (or
7781 // enum), the first typedef-name declared by the declaration
7782 // to be that class type (or enum type) is used to denote the
7783 // class type (or enum type) for linkage purposes only.
7784 // We need to check whether the type was declared in the declaration.
7785 switch (D.getDeclSpec().getTypeSpecType()) {
7786 case TST_enum:
7787 case TST_struct:
7788 case TST_union:
7789 case TST_class: {
7790 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7791
7792 // Do nothing if the tag is not anonymous or already has an
7793 // associated typedef (from an earlier typedef in this decl group).
7794 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +00007795 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +00007796
7797 // A well-formed anonymous tag must always be a TUK_Definition.
7798 assert(tagFromDeclSpec->isThisDeclarationADefinition());
7799
7800 // The type must match the tag exactly; no qualifiers allowed.
7801 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7802 break;
7803
7804 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +00007805 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +00007806 break;
7807 }
7808
7809 default:
7810 break;
7811 }
7812
Steve Naroff5912a352007-08-28 20:14:24 +00007813 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00007814}
7815
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007816
Richard Smithf1c66b42012-03-14 23:13:10 +00007817/// \brief Check that this is a valid underlying type for an enum declaration.
7818bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
7819 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7820 QualType T = TI->getType();
7821
7822 if (T->isDependentType() || T->isIntegralType(Context))
7823 return false;
7824
7825 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
7826 return true;
7827}
7828
7829/// Check whether this is a valid redeclaration of a previous enumeration.
7830/// \return true if the redeclaration was invalid.
7831bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
7832 QualType EnumUnderlyingTy,
7833 const EnumDecl *Prev) {
7834 bool IsFixed = !EnumUnderlyingTy.isNull();
7835
7836 if (IsScoped != Prev->isScoped()) {
7837 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
7838 << Prev->isScoped();
7839 Diag(Prev->getLocation(), diag::note_previous_use);
7840 return true;
7841 }
7842
7843 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +00007844 if (!EnumUnderlyingTy->isDependentType() &&
7845 !Prev->getIntegerType()->isDependentType() &&
7846 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +00007847 Prev->getIntegerType())) {
7848 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
7849 << EnumUnderlyingTy << Prev->getIntegerType();
7850 Diag(Prev->getLocation(), diag::note_previous_use);
7851 return true;
7852 }
7853 } else if (IsFixed != Prev->isFixed()) {
7854 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
7855 << Prev->isFixed();
7856 Diag(Prev->getLocation(), diag::note_previous_use);
7857 return true;
7858 }
7859
7860 return false;
7861}
7862
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007863/// \brief Determine whether a tag with a given kind is acceptable
7864/// as a redeclaration of the given tag declaration.
7865///
7866/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00007867bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +00007868 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007869 SourceLocation NewTagLoc,
7870 const IdentifierInfo &Name) {
7871 // C++ [dcl.type.elab]p3:
7872 // The class-key or enum keyword present in the
7873 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007874 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007875 // refers. This rule also applies to the form of
7876 // elaborated-type-specifier that declares a class-name or
7877 // friend class since it can be construed as referring to the
7878 // definition of the class. Thus, in any
7879 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007880 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007881 // used to refer to a union (clause 9), and either the class or
7882 // struct class-key shall be used to refer to a class (clause 9)
7883 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007884 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieubbf34c02011-06-10 03:11:26 +00007885 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7886 if (OldTag == NewTag)
7887 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007888
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007889 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7890 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007891 // Warn about the struct/class tag mismatch.
7892 bool isTemplate = false;
7893 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7894 isTemplate = Record->getDescribedClassTemplate();
7895
Richard Trieubbf34c02011-06-10 03:11:26 +00007896 if (!ActiveTemplateInstantiations.empty()) {
7897 // In a template instantiation, do not offer fix-its for tag mismatches
7898 // since they usually mess up the template instead of fixing the problem.
7899 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7900 << (NewTag == TTK_Class) << isTemplate << &Name;
7901 return true;
7902 }
7903
7904 if (isDefinition) {
7905 // On definitions, check previous tags and issue a fix-it for each
7906 // one that doesn't match the current tag.
7907 if (Previous->getDefinition()) {
7908 // Don't suggest fix-its for redefinitions.
7909 return true;
7910 }
7911
7912 bool previousMismatch = false;
7913 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7914 E(Previous->redecls_end()); I != E; ++I) {
7915 if (I->getTagKind() != NewTag) {
7916 if (!previousMismatch) {
7917 previousMismatch = true;
7918 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7919 << (NewTag == TTK_Class) << isTemplate << &Name;
7920 }
7921 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7922 << (NewTag == TTK_Class)
7923 << FixItHint::CreateReplacement(I->getInnerLocStart(),
7924 NewTag == TTK_Class?
7925 "class" : "struct");
7926 }
7927 }
7928 return true;
7929 }
7930
7931 // Check for a previous definition. If current tag and definition
7932 // are same type, do nothing. If no definition, but disagree with
7933 // with previous tag type, give a warning, but no fix-it.
7934 const TagDecl *Redecl = Previous->getDefinition() ?
7935 Previous->getDefinition() : Previous;
7936 if (Redecl->getTagKind() == NewTag) {
7937 return true;
7938 }
7939
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007940 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007941 << (NewTag == TTK_Class)
Richard Trieubbf34c02011-06-10 03:11:26 +00007942 << isTemplate << &Name;
7943 Diag(Redecl->getLocation(), diag::note_previous_use);
7944
7945 // If there is a previous defintion, suggest a fix-it.
7946 if (Previous->getDefinition()) {
7947 Diag(NewTagLoc, diag::note_struct_class_suggestion)
7948 << (Redecl->getTagKind() == TTK_Class)
7949 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7950 Redecl->getTagKind() == TTK_Class? "class" : "struct");
7951 }
7952
Douglas Gregor501c5ce2009-05-14 16:41:31 +00007953 return true;
7954 }
7955 return false;
7956}
7957
Steve Naroff08d92e42007-09-15 18:49:24 +00007958/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00007959/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +00007960/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00007961/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +00007962Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +00007963 SourceLocation KWLoc, CXXScopeSpec &SS,
7964 IdentifierInfo *Name, SourceLocation NameLoc,
7965 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +00007966 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +00007967 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00007968 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00007969 SourceLocation ScopedEnumKWLoc,
7970 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007971 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00007972 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +00007973 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +00007974 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +00007975 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +00007976 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +00007977
Douglas Gregor402abb52009-05-28 23:31:59 +00007978 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00007979 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +00007980 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +00007981
Douglas Gregor1fef4e62009-10-07 22:35:40 +00007982 // FIXME: Check explicit specializations more carefully.
7983 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +00007984 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +00007985
7986 // We only need to do this matching if we have template parameters
7987 // or a scope specifier, which also conveniently avoids this work
7988 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007989 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +00007990 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00007991 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00007992 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallbe04b6d2010-10-16 07:23:36 +00007993 TemplateParameterLists.get(),
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007994 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00007995 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00007996 isExplicitSpecialization,
7997 Invalid)) {
Douglas Gregord85bea22009-09-26 06:47:28 +00007998 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00007999 // This is a declaration or definition of a class template (which may
8000 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008001
Douglas Gregor0167f3c2010-07-14 23:14:12 +00008002 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +00008003 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008004
Douglas Gregor7cdbc582009-07-22 23:48:44 +00008005 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +00008006 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00008007 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008008 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +00008009 ModulePrivateLoc,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008010 TemplateParameterLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008011 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregor7cdbc582009-07-22 23:48:44 +00008012 return Result.get();
8013 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +00008014 // The "template<>" header is extraneous.
8015 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00008016 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +00008017 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +00008018 }
Mike Stump1eb44332009-09-09 15:08:12 +00008019 }
8020 }
8021
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008022 // Figure out the underlying type if this a enum declaration. We need to do
8023 // this early, because it's needed to detect if this is an incompatible
8024 // redeclaration.
8025 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8026
8027 if (Kind == TTK_Enum) {
8028 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8029 // No underlying type explicitly specified, or we failed to parse the
8030 // type, default to int.
8031 EnumUnderlying = Context.IntTy.getTypePtr();
8032 else if (UnderlyingType.get()) {
8033 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8034 // integral type; any cv-qualification is ignored.
8035 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +00008036 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008037 EnumUnderlying = TI;
8038
Richard Smithf1c66b42012-03-14 23:13:10 +00008039 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008040 // Recover by falling back to int.
8041 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +00008042
Richard Smithf1c66b42012-03-14 23:13:10 +00008043 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +00008044 UPPC_FixedUnderlyingType))
8045 EnumUnderlying = Context.IntTy.getTypePtr();
8046
David Blaikie4e4d0842012-03-11 07:00:24 +00008047 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +00008048 // Microsoft enums are always of int type.
8049 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008050 }
8051
Douglas Gregor4920f1f2009-01-12 22:49:06 +00008052 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00008053 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00008054 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008055
Chandler Carruth7bf36002010-03-01 21:17:36 +00008056 RedeclarationKind Redecl = ForRedeclaration;
8057 if (TUK == TUK_Friend || TUK == TUK_Reference)
8058 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +00008059
8060 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6e247262009-10-10 05:48:19 +00008061
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00008062 if (Name && SS.isNotEmpty()) {
8063 // We have a nested-name tag ('struct foo::bar').
8064
8065 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00008066 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00008067 Name = 0;
8068 goto CreateNewDecl;
8069 }
8070
John McCallc4e70192009-09-11 04:59:25 +00008071 // If this is a friend or a reference to a class in a dependent
8072 // context, don't try to make a decl for it.
8073 if (TUK == TUK_Friend || TUK == TUK_Reference) {
8074 DC = computeDeclContext(SS, false);
8075 if (!DC) {
8076 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +00008077 return 0;
John McCallc4e70192009-09-11 04:59:25 +00008078 }
John McCall77bb1aa2010-05-01 00:40:08 +00008079 } else {
8080 DC = computeDeclContext(SS, true);
8081 if (!DC) {
8082 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8083 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00008084 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +00008085 }
John McCallc4e70192009-09-11 04:59:25 +00008086 }
8087
John McCall77bb1aa2010-05-01 00:40:08 +00008088 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +00008089 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00008090
Douglas Gregor1931b442009-02-03 00:34:39 +00008091 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00008092 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +00008093 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +00008094
John McCall68263142009-11-18 22:49:29 +00008095 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00008096 return 0;
John McCall6e247262009-10-10 05:48:19 +00008097
John McCall68263142009-11-18 22:49:29 +00008098 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00008099 // Name lookup did not find anything. However, if the
8100 // nested-name-specifier refers to the current instantiation,
8101 // and that current instantiation has any dependent base
8102 // classes, we might find something at instantiation time: treat
8103 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +00008104 // But this only makes any sense for reference-like lookups.
8105 if (Previous.wasNotFoundInCurrentInstantiation() &&
8106 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00008107 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +00008108 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00008109 }
8110
8111 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +00008112 Diag(NameLoc, diag::err_not_tag_in_scope)
8113 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00008114 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +00008115 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00008116 goto CreateNewDecl;
8117 }
Chris Lattnercf79b012009-01-21 02:38:50 +00008118 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00008119 // If this is a named struct, check to see if there was a previous forward
8120 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00008121 // FIXME: We're looking into outer scopes here, even when we
8122 // shouldn't be. Doing so can result in ambiguities that we
8123 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +00008124 LookupName(Previous, S);
8125
Douglas Gregor93b6bce2011-05-09 21:46:33 +00008126 if (Previous.isAmbiguous() &&
8127 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +00008128 LookupResult::Filter F = Previous.makeFilter();
8129 while (F.hasNext()) {
8130 NamedDecl *ND = F.next();
8131 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8132 F.erase();
8133 }
8134 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +00008135 }
8136
John McCall68263142009-11-18 22:49:29 +00008137 // Note: there used to be some attempt at recovery here.
8138 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00008139 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +00008140
David Blaikie4e4d0842012-03-11 07:00:24 +00008141 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +00008142 // FIXME: This makes sure that we ignore the contexts associated
8143 // with C structs, unions, and enums when looking for a matching
8144 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00008145 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00008146 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8147 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00008148 }
Douglas Gregor069ea642010-09-16 23:58:57 +00008149 } else if (S->isFunctionPrototypeScope()) {
8150 // If this is an enum declaration in function prototype scope, set its
8151 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +00008152 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +00008153 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00008154 }
8155
John McCall68263142009-11-18 22:49:29 +00008156 if (Previous.isSingleResult() &&
8157 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00008158 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +00008159 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +00008160 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00008161 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00008162 }
8163
David Blaikie4e4d0842012-03-11 07:00:24 +00008164 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00008165 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00008166 // This is a declaration of or a reference to "std::bad_alloc".
8167 isStdBadAlloc = true;
8168
John McCall68263142009-11-18 22:49:29 +00008169 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00008170 // std::bad_alloc has been implicitly declared (but made invisible to
8171 // name lookup). Fill in this implicit declaration as the previous
8172 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00008173 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00008174 }
8175 }
John McCall68263142009-11-18 22:49:29 +00008176
John McCall9c86b512010-03-25 21:28:06 +00008177 // If we didn't find a previous declaration, and this is a reference
8178 // (or friend reference), move to the correct scope. In C++, we
8179 // also need to do a redeclaration lookup there, just in case
8180 // there's a shadow friend decl.
8181 if (Name && Previous.empty() &&
8182 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8183 if (Invalid) goto CreateNewDecl;
8184 assert(SS.isEmpty());
8185
8186 if (TUK == TUK_Reference) {
8187 // C++ [basic.scope.pdecl]p5:
8188 // -- for an elaborated-type-specifier of the form
8189 //
8190 // class-key identifier
8191 //
8192 // if the elaborated-type-specifier is used in the
8193 // decl-specifier-seq or parameter-declaration-clause of a
8194 // function defined in namespace scope, the identifier is
8195 // declared as a class-name in the namespace that contains
8196 // the declaration; otherwise, except as a friend
8197 // declaration, the identifier is declared in the smallest
8198 // non-class, non-function-prototype scope that contains the
8199 // declaration.
8200 //
8201 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8202 // C structs and unions.
8203 //
8204 // It is an error in C++ to declare (rather than define) an enum
8205 // type, including via an elaborated type specifier. We'll
8206 // diagnose that later; for now, declare the enum in the same
8207 // scope as we would have picked for any other tag type.
8208 //
8209 // GNU C also supports this behavior as part of its incomplete
8210 // enum types extension, while GNU C++ does not.
8211 //
8212 // Find the context where we'll be declaring the tag.
8213 // FIXME: We would like to maintain the current DeclContext as the
8214 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +00008215 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +00008216 SearchDC = SearchDC->getParent();
8217
8218 // Find the scope where we'll be declaring the tag.
8219 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00008220 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +00008221 S->isFunctionPrototypeScope()) ||
8222 ((S->getFlags() & Scope::DeclScope) == 0) ||
8223 (S->getEntity() &&
8224 ((DeclContext *)S->getEntity())->isTransparentContext()))
8225 S = S->getParent();
8226 } else {
8227 assert(TUK == TUK_Friend);
8228 // C++ [namespace.memdef]p3:
8229 // If a friend declaration in a non-local class first declares a
8230 // class or function, the friend class or function is a member of
8231 // the innermost enclosing namespace.
8232 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +00008233 }
8234
John McCall0d6b1642010-04-23 18:46:30 +00008235 // In C++, we need to do a redeclaration lookup to properly
8236 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +00008237 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +00008238 Previous.setRedeclarationKind(ForRedeclaration);
8239 LookupQualifiedName(Previous, SearchDC);
8240 }
8241 }
8242
John McCall68263142009-11-18 22:49:29 +00008243 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +00008244 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +00008245
8246 // It's okay to have a tag decl in the same scope as a typedef
8247 // which hides a tag decl in the same scope. Finding this
8248 // insanity with a redeclaration lookup can only actually happen
8249 // in C++.
8250 //
8251 // This is also okay for elaborated-type-specifiers, which is
8252 // technically forbidden by the current standard but which is
8253 // okay according to the likely resolution of an open issue;
8254 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +00008255 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +00008256 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +00008257 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8258 TagDecl *Tag = TT->getDecl();
8259 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00008260 Tag->getDeclContext()->getRedeclContext()
8261 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +00008262 PrevDecl = Tag;
8263 Previous.clear();
8264 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +00008265 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +00008266 }
8267 }
8268 }
8269 }
8270
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00008271 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00008272 // If this is a use of a previous tag, or if the tag is already declared
8273 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00008274 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +00008275 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +00008276 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +00008277 // Make sure that this wasn't declared as an enum and now used as a
8278 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +00008279 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8280 TUK == TUK_Definition, KWLoc,
8281 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +00008282 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +00008283 = (PrevTagDecl->getTagKind() != TTK_Enum &&
8284 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +00008285 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +00008286 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00008287 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +00008288 << FixItHint::CreateReplacement(SourceRange(KWLoc),
8289 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +00008290 else
8291 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +00008292 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +00008293
Mike Stump1eb44332009-09-09 15:08:12 +00008294 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +00008295 Kind = PrevTagDecl->getTagKind();
8296 else {
8297 // Recover by making this an anonymous redefinition.
8298 Name = 0;
John McCall68263142009-11-18 22:49:29 +00008299 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +00008300 Invalid = true;
8301 }
8302 }
8303
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008304 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8305 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8306
Richard Smithbdad7a22012-01-10 01:33:14 +00008307 // If this is an elaborated-type-specifier for a scoped enumeration,
8308 // the 'class' keyword is not necessary and not permitted.
8309 if (TUK == TUK_Reference || TUK == TUK_Friend) {
8310 if (ScopedEnum)
8311 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8312 << PrevEnum->isScoped()
8313 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8314 return PrevTagDecl;
8315 }
8316
Richard Smithf1c66b42012-03-14 23:13:10 +00008317 QualType EnumUnderlyingTy;
8318 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8319 EnumUnderlyingTy = TI->getType();
8320 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8321 EnumUnderlyingTy = QualType(T, 0);
8322
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008323 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +00008324 // returning the previous declaration, unless this is a definition,
8325 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +00008326 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8327 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +00008328 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008329 }
8330
Douglas Gregora3a83512009-04-01 23:51:29 +00008331 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008332 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00008333
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008334 // FIXME: In the future, return a variant or some other clue
8335 // for the consumer of this Decl to know it doesn't own it.
8336 // For our current ASTs this shouldn't be a problem, but will
8337 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +00008338 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00008339 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +00008340 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +00008341
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008342 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +00008343 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00008344 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008345 // If we're defining a specialization and the previous definition
8346 // is from an implicit instantiation, don't emit an error
8347 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +00008348 bool IsExplicitSpecializationAfterInstantiation = false;
8349 if (isExplicitSpecialization) {
8350 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8351 IsExplicitSpecializationAfterInstantiation =
8352 RD->getTemplateSpecializationKind() !=
8353 TSK_ExplicitSpecialization;
8354 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8355 IsExplicitSpecializationAfterInstantiation =
8356 ED->getTemplateSpecializationKind() !=
8357 TSK_ExplicitSpecialization;
8358 }
8359
8360 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +00008361 // A redeclaration in function prototype scope in C isn't
8362 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +00008363 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +00008364 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8365 else
8366 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008367 Diag(Def->getLocation(), diag::note_previous_definition);
8368 // If this is a redefinition, recover by making this
8369 // struct be anonymous, which will make any later
8370 // references get the previous definition.
8371 Name = 0;
John McCall68263142009-11-18 22:49:29 +00008372 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008373 Invalid = true;
8374 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008375 } else {
8376 // If the type is currently being defined, complain
8377 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +00008378 const TagType *Tag
8379 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008380 if (Tag->isBeingDefined()) {
8381 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +00008382 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008383 diag::note_previous_definition);
8384 Name = 0;
John McCall68263142009-11-18 22:49:29 +00008385 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008386 Invalid = true;
8387 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008388 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008389
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008390 // Okay, this is definition of a previously declared or referenced
8391 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008392 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00008393 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008394 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +00008395 // have a definition. Just create a new decl.
8396
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008397 } else {
8398 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +00008399 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008400 // new decl/type. We set PrevDecl to NULL so that the entities
8401 // have distinct types.
John McCall68263142009-11-18 22:49:29 +00008402 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00008403 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008404 // If we get here, we're going to create a new Decl. If PrevDecl
8405 // is non-NULL, it's a definition of the tag declared by
8406 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +00008407
8408
8409 // Otherwise, PrevDecl is not a tag, but was found with tag
8410 // lookup. This is only actually possible in C++, where a few
8411 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00008412 } else {
John McCall0d6b1642010-04-23 18:46:30 +00008413 // Use a better diagnostic if an elaborated-type-specifier
8414 // found the wrong kind of type on the first
8415 // (non-redeclaration) lookup.
8416 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8417 !Previous.isForRedeclaration()) {
8418 unsigned Kind = 0;
8419 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +00008420 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8421 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +00008422 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8423 Diag(PrevDecl->getLocation(), diag::note_declared_at);
8424 Invalid = true;
8425
8426 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +00008427 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8428 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +00008429 // do nothing
8430
8431 // Diagnose implicit declarations introduced by elaborated types.
8432 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8433 unsigned Kind = 0;
8434 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +00008435 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8436 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +00008437 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8438 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8439 Invalid = true;
8440
8441 // Otherwise it's a declaration. Call out a particularly common
8442 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +00008443 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8444 unsigned Kind = 0;
8445 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +00008446 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +00008447 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +00008448 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8449 Invalid = true;
8450
8451 // Otherwise, diagnose.
8452 } else {
8453 // The tag name clashes with something else in the target scope,
8454 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00008455 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00008456 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00008457 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008458 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00008459 }
John McCall0d6b1642010-04-23 18:46:30 +00008460
8461 // The existing declaration isn't relevant to us; we're in a
8462 // new scope, so clear out the previous declaration.
8463 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00008464 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008465 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00008466
Chris Lattnercc98eac2008-12-17 07:13:27 +00008467CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +00008468
John McCall68263142009-11-18 22:49:29 +00008469 TagDecl *PrevDecl = 0;
8470 if (Previous.isSingleResult())
8471 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8472
Reid Spencer5f016e22007-07-11 17:01:13 +00008473 // If there is an identifier, use the location of the identifier as the
8474 // location of the decl, otherwise use the location of the struct/union
8475 // keyword.
8476 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00008477
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008478 // Otherwise, create a new declaration. If there is a previous
8479 // declaration of the same entity, the two will be linked via
8480 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00008481 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00008482
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008483 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00008484 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008485 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8486 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00008487 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008488 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00008489 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +00008490 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00008491 if (TUK != TUK_Definition && !Invalid) {
8492 TagDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00008493 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008494 // C++0x: 7.2p2: opaque-enum-declaration.
8495 // Conflicts are diagnosed above. Do nothing.
8496 }
8497 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00008498 Diag(Loc, diag::ext_forward_ref_enum_def)
8499 << New;
8500 Diag(Def->getLocation(), diag::note_previous_definition);
8501 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +00008502 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +00008503 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +00008504 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +00008505 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +00008506 DiagID = diag::err_forward_ref_enum;
8507 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008508
8509 // If this is a forward-declared reference to an enumeration, make a
8510 // note of it; we won't actually be introducing the declaration into
8511 // the declaration context.
8512 if (TUK == TUK_Reference)
8513 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00008514 }
Douglas Gregor80711a22009-03-06 18:34:03 +00008515 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008516
8517 if (EnumUnderlying) {
8518 EnumDecl *ED = cast<EnumDecl>(New);
8519 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8520 ED->setIntegerTypeSourceInfo(TI);
8521 else
8522 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8523 ED->setPromotionType(ED->getIntegerType());
8524 }
8525
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00008526 } else {
8527 // struct/union/class
8528
Reid Spencer5f016e22007-07-11 17:01:13 +00008529 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8530 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +00008531 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +00008532 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00008533 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008534 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00008535
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00008536 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +00008537 StdBadAlloc = cast<CXXRecordDecl>(New);
8538 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00008539 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008540 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00008541 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008542
John McCallb6217662010-03-15 10:12:16 +00008543 // Maybe add qualifier info.
8544 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00008545 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +00008546 // If this is either a declaration or a definition, check the
8547 // nested-name-specifier against the current context. We don't do this
8548 // for explicit specializations, because they have similar checking
8549 // (with more specific diagnostics) in the call to
8550 // CheckMemberSpecialization, below.
8551 if (!isExplicitSpecialization &&
8552 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
8553 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
8554 Invalid = true;
8555
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00008556 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008557 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00008558 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008559 TemplateParameterLists.size(),
Abramo Bagnara9b934882010-06-12 08:15:14 +00008560 (TemplateParameterList**) TemplateParameterLists.release());
8561 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00008562 }
8563 else
8564 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +00008565 }
8566
Daniel Dunbar9f21f892010-05-27 01:53:40 +00008567 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8568 // Add alignment attributes if necessary; these attributes are checked when
8569 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008570 //
8571 // It is important for implementing the correct semantics that this
8572 // happen here (in act on tag decl). The #pragma pack stack is
8573 // maintained as a result of parser callbacks which can occur at
8574 // many points during the parsing of a struct declaration (because
8575 // the #pragma tokens are effectively skipped over during the
8576 // parsing of the struct).
Daniel Dunbar9f21f892010-05-27 01:53:40 +00008577 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanianc1a0a732011-04-26 17:54:40 +00008578
8579 AddMsStructLayoutForRecord(RD);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008580 }
8581
Douglas Gregor2ccd89c2011-12-20 18:11:52 +00008582 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00008583 if (isExplicitSpecialization)
8584 Diag(New->getLocation(), diag::err_module_private_specialization)
8585 << 2
8586 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +00008587 // __module_private__ does not apply to local classes. However, we only
8588 // diagnose this as an error when the declaration specifiers are
8589 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +00008590 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +00008591 New->setModulePrivate();
8592 }
8593
Douglas Gregorf6b11852009-10-08 15:14:33 +00008594 // If this is a specialization of a member class (of a class template),
8595 // check the specialization.
John McCall68263142009-11-18 22:49:29 +00008596 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +00008597 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +00008598
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008599 if (Invalid)
8600 New->setInvalidDecl();
8601
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008602 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008603 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008604
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008605 // If we're declaring or defining a tag in function prototype scope
8606 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +00008607 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +00008608 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8609
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00008610 // Set the lexical context. If the tag has a C++ scope specifier, the
8611 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00008612 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008613
John McCall02cace72009-08-28 07:59:38 +00008614 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +00008615 // In Microsoft mode, a friend declaration also acts as a forward
8616 // declaration so we always pass true to setObjectOfFriendDecl to make
8617 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +00008618 if (TUK == TUK_Friend)
Francois Pichetb4746032011-06-01 04:14:20 +00008619 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00008620 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +00008621
Anders Carlsson0cf88302009-03-26 01:19:02 +00008622 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +00008623 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +00008624 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +00008625
John McCall0f434ec2009-07-31 02:45:11 +00008626 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +00008627 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00008628
Reid Spencer5f016e22007-07-11 17:01:13 +00008629 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +00008630 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +00008631 // We might be replacing an existing declaration in the lookup tables;
8632 // if so, borrow its access specifier.
8633 if (PrevDecl)
8634 New->setAccess(PrevDecl->getAccess());
8635
Sebastian Redl7a126a42010-08-31 00:36:30 +00008636 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00008637 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +00008638 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +00008639 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8640 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +00008641 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00008642 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008643 PushOnScopeChains(New, S, !IsForwardReference);
8644 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +00008645 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00008646
Douglas Gregor4920f1f2009-01-12 22:49:06 +00008647 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008648 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00008649 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00008650
Douglas Gregorc29f77b2009-07-07 16:35:42 +00008651 // If this is the C FILE type, notify the AST context.
8652 if (IdentifierInfo *II = New->getIdentifier())
8653 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00008654 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +00008655 II->isStr("FILE"))
8656 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +00008657
James Molloy16f1f712012-02-29 10:24:19 +00008658 // If we were in function prototype scope (and not in C++ mode), add this
8659 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +00008660 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +00008661 InFunctionDeclarator && Name)
8662 DeclsInPrototypeScope.push_back(New);
8663
Douglas Gregor402abb52009-05-28 23:31:59 +00008664 OwnedDecl = true;
John McCalld226f652010-08-21 09:40:31 +00008665 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00008666}
8667
John McCalld226f652010-08-21 09:40:31 +00008668void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00008669 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00008670 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +00008671
Douglas Gregor72de6672009-01-08 20:45:30 +00008672 // Enter the tag context.
8673 PushDeclContext(S, Tag);
John McCallf9368152009-12-20 07:58:13 +00008674}
Douglas Gregor72de6672009-01-08 20:45:30 +00008675
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00008676Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00008677 assert(isa<ObjCContainerDecl>(IDecl) &&
8678 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8679 DeclContext *OCD = cast<DeclContext>(IDecl);
8680 assert(getContainingDC(OCD) == CurContext &&
8681 "The next DeclContext should be lexically contained in the current one.");
8682 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00008683 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00008684}
8685
John McCalld226f652010-08-21 09:40:31 +00008686void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +00008687 SourceLocation FinalLoc,
John McCallf9368152009-12-20 07:58:13 +00008688 SourceLocation LBraceLoc) {
8689 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00008690 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00008691
John McCallf9368152009-12-20 07:58:13 +00008692 FieldCollector->StartClass();
8693
8694 if (!Record->getIdentifier())
8695 return;
8696
Anders Carlsson2c3ee542011-03-25 14:31:08 +00008697 if (FinalLoc.isValid())
8698 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssondfc2f102011-01-22 17:51:53 +00008699
John McCallf9368152009-12-20 07:58:13 +00008700 // C++ [class]p2:
8701 // [...] The class-name is also inserted into the scope of the
8702 // class itself; this is known as the injected-class-name. For
8703 // purposes of access checking, the injected-class-name is treated
8704 // as if it were a public member name.
8705 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00008706 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8707 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +00008708 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +00008709 /*PrevDecl=*/0,
8710 /*DelayTypeCreation=*/true);
8711 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +00008712 InjectedClassName->setImplicit();
8713 InjectedClassName->setAccess(AS_public);
8714 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8715 InjectedClassName->setDescribedClassTemplate(Template);
8716 PushOnScopeChains(InjectedClassName, S);
8717 assert(InjectedClassName->isInjectedClassName() &&
8718 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +00008719}
8720
John McCalld226f652010-08-21 09:40:31 +00008721void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00008722 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00008723 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00008724 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00008725 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +00008726
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00008727 // Make sure we "complete" the definition even it is invalid.
8728 if (Tag->isBeingDefined()) {
8729 assert(Tag->isInvalidDecl() && "We should already have completed it");
8730 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8731 RD->completeDefinition();
8732 }
8733
Douglas Gregor72de6672009-01-08 20:45:30 +00008734 if (isa<CXXRecordDecl>(Tag))
8735 FieldCollector->FinishClass();
8736
8737 // Exit this scope of this tag's definition.
8738 PopDeclContext();
Douglas Gregoradda8462010-01-06 17:00:51 +00008739
Douglas Gregor72de6672009-01-08 20:45:30 +00008740 // Notify the consumer that we've defined a tag.
8741 Consumer.HandleTagDeclDefinition(Tag);
8742}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00008743
Fariborz Jahanian10af8792011-08-29 17:33:12 +00008744void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00008745 // Exit this scope of this interface definition.
8746 PopDeclContext();
8747}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00008748
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +00008749void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +00008750 assert(DC == CurContext && "Mismatch of container contexts");
8751 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00008752 ActOnObjCContainerFinishDefinition();
8753}
8754
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +00008755void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8756 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00008757 OriginalLexicalContext = 0;
8758}
8759
John McCalld226f652010-08-21 09:40:31 +00008760void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +00008761 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00008762 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +00008763 Tag->setInvalidDecl();
8764
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00008765 // Make sure we "complete" the definition even it is invalid.
8766 if (Tag->isBeingDefined()) {
8767 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8768 RD->completeDefinition();
8769 }
8770
John McCalla8cab012010-03-17 19:25:57 +00008771 // We're undoing ActOnTagStartDefinition here, not
8772 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8773 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +00008774
8775 PopDeclContext();
8776}
8777
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008778// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +00008779ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
8780 IdentifierInfo *FieldName,
8781 QualType FieldTy, Expr *BitWidth,
8782 bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +00008783 // Default to true; that shouldn't confuse checks for emptiness
8784 if (ZeroWidth)
8785 *ZeroWidth = true;
8786
Chris Lattner24793662009-03-05 22:45:59 +00008787 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +00008788 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00008789 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +00008790 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +00008791 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +00008792 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008793 if (FieldName)
8794 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8795 << FieldName << FieldTy << BitWidth->getSourceRange();
8796 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8797 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +00008798 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8799 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +00008800 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008801
8802 // If the bit-width is type- or value-dependent, don't try to check
8803 // it now.
8804 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +00008805 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008806
Anders Carlsson9f1e5722008-12-06 20:33:04 +00008807 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00008808 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
8809 if (ICE.isInvalid())
8810 return ICE;
8811 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +00008812
Eli Friedman1d954f62009-08-15 21:55:26 +00008813 if (Value != 0 && ZeroWidth)
8814 *ZeroWidth = false;
8815
Chris Lattnercd087072008-12-12 04:56:04 +00008816 // Zero-width bitfield is ok for anonymous field.
8817 if (Value == 0 && FieldName)
8818 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00008819
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008820 if (Value.isSigned() && Value.isNegative()) {
8821 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +00008822 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008823 << FieldName << Value.toString(10);
8824 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8825 << Value.toString(10);
8826 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00008827
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008828 if (!FieldTy->isDependentType()) {
8829 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008830 if (Value.getZExtValue() > TypeSize) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008831 if (!getLangOpts().CPlusPlus) {
Anders Carlsson72468ec2010-04-16 15:16:32 +00008832 if (FieldName)
8833 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8834 << FieldName << (unsigned)Value.getZExtValue()
8835 << (unsigned)TypeSize;
8836
8837 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8838 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8839 }
8840
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008841 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +00008842 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8843 << FieldName << (unsigned)Value.getZExtValue()
8844 << (unsigned)TypeSize;
8845 else
8846 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8847 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00008848 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008849 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00008850
Richard Smith282e7e62012-02-04 09:53:13 +00008851 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +00008852}
8853
Richard Smith7a614d82011-06-11 17:19:42 +00008854/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00008855/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +00008856Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +00008857 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +00008858 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +00008859 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith7a614d82011-06-11 17:19:42 +00008860 /*HasInit=*/false, AS_public);
John McCalld226f652010-08-21 09:40:31 +00008861 return Res;
Chris Lattner24793662009-03-05 22:45:59 +00008862}
8863
8864/// HandleField - Analyze a field of a C struct or a C++ data member.
8865///
8866FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8867 SourceLocation DeclStart,
Richard Smith7a614d82011-06-11 17:19:42 +00008868 Declarator &D, Expr *BitWidth, bool HasInit,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00008869 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008870 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00008871 SourceLocation Loc = DeclStart;
8872 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00008873
John McCallbf1a0282010-06-04 23:28:52 +00008874 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8875 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00008876 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008877 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00008878
Douglas Gregore1862692010-12-15 23:18:36 +00008879 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8880 UPPC_DataMemberType)) {
8881 D.setInvalidType();
8882 T = Context.IntTy;
8883 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8884 }
8885 }
8886
Eli Friedman85a53192009-04-07 19:37:57 +00008887 DiagnoseFunctionSpecifiers(D);
8888
Eli Friedman63054b32009-04-19 20:27:55 +00008889 if (D.getDeclSpec().isThreadSpecified())
8890 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008891 if (D.getDeclSpec().isConstexprSpecified())
8892 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8893 << 2;
Douglas Gregor7f6ff022010-08-30 14:32:14 +00008894
8895 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +00008896 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +00008897 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8898 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +00008899 switch (Previous.getResultKind()) {
8900 case LookupResult::Found:
8901 case LookupResult::FoundUnresolvedValue:
8902 PrevDecl = Previous.getAsSingle<NamedDecl>();
8903 break;
8904
8905 case LookupResult::FoundOverloaded:
8906 PrevDecl = Previous.getRepresentativeDecl();
8907 break;
8908
8909 case LookupResult::NotFound:
8910 case LookupResult::NotFoundInCurrentInstantiation:
8911 case LookupResult::Ambiguous:
8912 break;
8913 }
8914 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +00008915
8916 if (PrevDecl && PrevDecl->isTemplateParameter()) {
8917 // Maybe we will complain about the shadowed template parameter.
8918 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8919 // Just pretend that we didn't see the previous declaration.
8920 PrevDecl = 0;
8921 }
8922
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008923 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8924 PrevDecl = 0;
8925
Steve Naroffea218b82009-07-14 14:58:18 +00008926 bool Mutable
8927 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +00008928 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +00008929 FieldDecl *NewFD
Richard Smith7a614d82011-06-11 17:19:42 +00008930 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8931 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +00008932
8933 if (NewFD->isInvalidDecl())
8934 Record->setInvalidDecl();
8935
Douglas Gregor591dc842011-09-12 16:11:24 +00008936 if (D.getDeclSpec().isModulePrivateSpecified())
8937 NewFD->setModulePrivate();
8938
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008939 if (NewFD->isInvalidDecl() && PrevDecl) {
8940 // Don't introduce NewFD into scope; there's already something
8941 // with the same name in the same scope.
8942 } else if (II) {
8943 PushOnScopeChains(NewFD, S);
8944 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008945 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008946
8947 return NewFD;
8948}
8949
8950/// \brief Build a new FieldDecl and check its well-formedness.
8951///
8952/// This routine builds a new FieldDecl given the fields name, type,
8953/// record, etc. \p PrevDecl should refer to any previous declaration
8954/// with the same name and in the same scope as the field to be
8955/// created.
8956///
8957/// \returns a new FieldDecl.
8958///
Mike Stump1eb44332009-09-09 15:08:12 +00008959/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00008960FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00008961 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008962 RecordDecl *Record, SourceLocation Loc,
Richard Smith7a614d82011-06-11 17:19:42 +00008963 bool Mutable, Expr *BitWidth, bool HasInit,
Steve Naroffea218b82009-07-14 14:58:18 +00008964 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00008965 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008966 Declarator *D) {
8967 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +00008968 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +00008969 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +00008970
Douglas Gregor3cf538d2009-03-11 18:59:21 +00008971 // If we receive a broken type, recover by assuming 'int' and
8972 // marking this declaration as invalid.
8973 if (T.isNull()) {
8974 InvalidDecl = true;
8975 T = Context.IntTy;
8976 }
8977
Eli Friedman721e77d2009-12-07 00:22:08 +00008978 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00008979 if (!EltTy->isDependentType()) {
8980 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8981 // Fields of incomplete type force their record to be invalid.
8982 Record->setInvalidDecl();
8983 InvalidDecl = true;
8984 } else {
8985 NamedDecl *Def;
8986 EltTy->isIncompleteType(&Def);
8987 if (Def && Def->isInvalidDecl()) {
8988 Record->setInvalidDecl();
8989 InvalidDecl = true;
8990 }
8991 }
John McCall2d7d2d92010-08-16 23:42:35 +00008992 }
Eli Friedman721e77d2009-12-07 00:22:08 +00008993
Reid Spencer5f016e22007-07-11 17:01:13 +00008994 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8995 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +00008996 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00008997 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00008998 llvm::APSInt Oversized;
Eli Friedman1ca48132009-02-21 00:44:51 +00008999 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00009000 SizeIsNegative,
9001 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00009002 if (!FixedTy.isNull()) {
9003 Diag(Loc, diag::warn_illegal_constant_array_size);
9004 T = FixedTy;
9005 } else {
9006 if (SizeIsNegative)
9007 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +00009008 else if (Oversized.getBoolValue())
9009 Diag(Loc, diag::err_array_too_large)
9010 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00009011 else
9012 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00009013 InvalidDecl = true;
9014 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009015 }
Mike Stump1eb44332009-09-09 15:08:12 +00009016
Anders Carlsson4681ebd2009-03-22 20:18:17 +00009017 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +00009018 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9019 diag::err_abstract_type_in_decl,
9020 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +00009021 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00009022
Eli Friedman1d954f62009-08-15 21:55:26 +00009023 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00009024 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +00009025 if (!InvalidDecl && BitWidth) {
9026 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9027 if (!BitWidth) {
9028 InvalidDecl = true;
9029 BitWidth = 0;
9030 ZeroWidth = false;
9031 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00009032 }
Mike Stump1eb44332009-09-09 15:08:12 +00009033
John McCall4bde1e12010-06-04 08:34:12 +00009034 // Check that 'mutable' is consistent with the type of the declaration.
9035 if (!InvalidDecl && Mutable) {
9036 unsigned DiagID = 0;
9037 if (T->isReferenceType())
9038 DiagID = diag::err_mutable_reference;
9039 else if (T.isConstQualified())
9040 DiagID = diag::err_mutable_const;
9041
9042 if (DiagID) {
9043 SourceLocation ErrLoc = Loc;
9044 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9045 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9046 Diag(ErrLoc, DiagID);
9047 Mutable = false;
9048 InvalidDecl = true;
9049 }
9050 }
9051
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009052 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00009053 BitWidth, Mutable, HasInit);
Chris Lattnereaaebc72009-04-25 08:06:05 +00009054 if (InvalidDecl)
9055 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00009056
Douglas Gregor3cf538d2009-03-11 18:59:21 +00009057 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9058 Diag(Loc, diag::err_duplicate_member) << II;
9059 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9060 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +00009061 }
9062
David Blaikie4e4d0842012-03-11 07:00:24 +00009063 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +00009064 if (Record->isUnion()) {
9065 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9066 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9067 if (RDecl->getDefinition()) {
9068 // C++ [class.union]p1: An object of a class with a non-trivial
9069 // constructor, a non-trivial copy constructor, a non-trivial
9070 // destructor, or a non-trivial copy assignment operator
9071 // cannot be a member of a union, nor can an array of such
9072 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00009073 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +00009074 NewFD->setInvalidDecl();
9075 }
9076 }
9077
9078 // C++ [class.union]p1: If a union contains a member of reference type,
9079 // the program is ill-formed.
9080 if (EltTy->isReferenceType()) {
9081 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9082 << NewFD->getDeclName() << EltTy;
9083 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009084 }
9085 }
9086 }
9087
Douglas Gregor3cf538d2009-03-11 18:59:21 +00009088 // FIXME: We need to pass in the attributes given an AST
9089 // representation, not a parser representation.
9090 if (D)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009091 // FIXME: What to pass instead of TUScope?
9092 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00009093
John McCallf85e1932011-06-15 23:02:42 +00009094 // In auto-retain/release, infer strong retension for fields of
9095 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009096 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +00009097 NewFD->setInvalidDecl();
9098
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00009099 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00009100 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00009101
Douglas Gregor4dd55f52009-03-11 20:50:30 +00009102 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +00009103 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009104}
9105
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00009106bool Sema::CheckNontrivialField(FieldDecl *FD) {
9107 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +00009108 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00009109
9110 if (FD->isInvalidDecl())
9111 return true;
9112
9113 QualType EltTy = Context.getBaseElementType(FD->getType());
9114 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9115 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9116 if (RDecl->getDefinition()) {
9117 // We check for copy constructors before constructors
9118 // because otherwise we'll never get complaints about
9119 // copy constructors.
9120
9121 CXXSpecialMember member = CXXInvalid;
9122 if (!RDecl->hasTrivialCopyConstructor())
9123 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +00009124 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +00009125 member = CXXDefaultConstructor;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00009126 else if (!RDecl->hasTrivialCopyAssignment())
9127 member = CXXCopyAssignment;
9128 else if (!RDecl->hasTrivialDestructor())
9129 member = CXXDestructor;
9130
9131 if (member != CXXInvalid) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009132 if (!getLangOpts().CPlusPlus0x &&
9133 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +00009134 // Objective-C++ ARC: it is an error to have a non-trivial field of
9135 // a union. However, system headers in Objective-C programs
9136 // occasionally have Objective-C lifetime objects within unions,
9137 // and rather than cause the program to fail, we make those
9138 // members unavailable.
9139 SourceLocation Loc = FD->getLocation();
9140 if (getSourceManager().isInSystemHeader(Loc)) {
9141 if (!FD->hasAttr<UnavailableAttr>())
9142 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009143 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +00009144 return false;
9145 }
9146 }
Richard Smithe7d7c392011-10-19 20:41:51 +00009147
David Blaikie4e4d0842012-03-11 07:00:24 +00009148 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
Richard Smithe7d7c392011-10-19 20:41:51 +00009149 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9150 diag::err_illegal_union_or_anon_struct_member)
9151 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00009152 DiagnoseNontrivial(RT, member);
David Blaikie4e4d0842012-03-11 07:00:24 +00009153 return !getLangOpts().CPlusPlus0x;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00009154 }
9155 }
9156 }
9157
9158 return false;
9159}
9160
Richard Smithea7c1e22012-02-26 10:50:32 +00009161/// If the given constructor is user-provided, produce a diagnostic explaining
9162/// that it makes the class non-trivial.
9163static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9164 CXXConstructorDecl *CD,
9165 Sema::CXXSpecialMember CSM) {
9166 if (!CD->isUserProvided())
9167 return false;
9168
9169 SourceLocation CtorLoc = CD->getLocation();
9170 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9171 return true;
9172}
9173
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009174/// DiagnoseNontrivial - Given that a class has a non-trivial
9175/// special member, figure out why.
9176void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9177 QualType QT(T, 0U);
9178 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9179
9180 // Check whether the member was user-declared.
9181 switch (member) {
Douglas Gregor66dd9392010-04-22 14:36:26 +00009182 case CXXInvalid:
9183 break;
9184
Sean Huntf961ea52011-05-10 19:08:14 +00009185 case CXXDefaultConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009186 if (RD->hasUserDeclaredConstructor()) {
9187 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Richard Smithea7c1e22012-02-26 10:50:32 +00009188 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9189 if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009190 return;
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009191
Richard Smithea7c1e22012-02-26 10:50:32 +00009192 // No user-provided constructors; look for constructor templates.
9193 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9194 tmpl_iter;
9195 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9196 TI != TE; ++TI) {
9197 CXXConstructorDecl *CD =
9198 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9199 if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9200 return;
9201 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009202 }
9203 break;
9204
9205 case CXXCopyConstructor:
9206 if (RD->hasUserDeclaredCopyConstructor()) {
9207 SourceLocation CtorLoc =
Sean Huntffe37fd2011-05-25 20:50:04 +00009208 RD->getCopyConstructor(0)->getLocation();
9209 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9210 return;
9211 }
9212 break;
9213
9214 case CXXMoveConstructor:
9215 if (RD->hasUserDeclaredMoveConstructor()) {
9216 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009217 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9218 return;
9219 }
9220 break;
9221
9222 case CXXCopyAssignment:
9223 if (RD->hasUserDeclaredCopyAssignment()) {
9224 // FIXME: this should use the location of the copy
9225 // assignment, not the type.
Daniel Dunbar96a00142012-03-09 18:35:03 +00009226 SourceLocation TyLoc = RD->getLocStart();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009227 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9228 return;
9229 }
9230 break;
9231
Sean Huntffe37fd2011-05-25 20:50:04 +00009232 case CXXMoveAssignment:
9233 if (RD->hasUserDeclaredMoveAssignment()) {
9234 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9235 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9236 return;
9237 }
9238 break;
9239
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009240 case CXXDestructor:
9241 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00009242 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009243 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9244 return;
9245 }
9246 break;
9247 }
9248
9249 typedef CXXRecordDecl::base_class_iterator base_iter;
9250
9251 // Virtual bases and members inhibit trivial copying/construction,
9252 // but not trivial destruction.
9253 if (member != CXXDestructor) {
9254 // Check for virtual bases. vbases includes indirect virtual bases,
9255 // so we just iterate through the direct bases.
9256 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9257 if (bi->isVirtual()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009258 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009259 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9260 return;
9261 }
9262
9263 // Check for virtual methods.
9264 typedef CXXRecordDecl::method_iterator meth_iter;
9265 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9266 ++mi) {
9267 if (mi->isVirtual()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009268 SourceLocation MLoc = mi->getLocStart();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009269 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9270 return;
9271 }
9272 }
9273 }
Mike Stump1eb44332009-09-09 15:08:12 +00009274
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009275 bool (CXXRecordDecl::*hasTrivial)() const;
9276 switch (member) {
Sean Huntf961ea52011-05-10 19:08:14 +00009277 case CXXDefaultConstructor:
Sean Hunt023df372011-05-09 18:22:59 +00009278 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009279 case CXXCopyConstructor:
9280 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9281 case CXXCopyAssignment:
9282 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9283 case CXXDestructor:
9284 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9285 default:
David Blaikieeb2d1f12011-09-23 20:26:49 +00009286 llvm_unreachable("unexpected special member");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009287 }
9288
9289 // Check for nontrivial bases (and recurse).
9290 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenek6217b802009-07-29 21:53:49 +00009291 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl9994a342009-10-25 17:03:50 +00009292 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009293 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9294 if (!(BaseRecTy->*hasTrivial)()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009295 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009296 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9297 DiagnoseNontrivial(BaseRT, member);
9298 return;
9299 }
9300 }
Mike Stump1eb44332009-09-09 15:08:12 +00009301
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009302 // Check for nontrivial members (and recurse).
9303 typedef RecordDecl::field_iterator field_iter;
9304 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9305 ++fi) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00009306 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenek6217b802009-07-29 21:53:49 +00009307 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009308 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9309
9310 if (!(EltRD->*hasTrivial)()) {
9311 SourceLocation FLoc = (*fi)->getLocation();
9312 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9313 DiagnoseNontrivial(EltRT, member);
9314 return;
9315 }
9316 }
John McCallf85e1932011-06-15 23:02:42 +00009317
9318 if (EltTy->isObjCLifetimeType()) {
9319 switch (EltTy.getObjCLifetime()) {
9320 case Qualifiers::OCL_None:
9321 case Qualifiers::OCL_ExplicitNone:
9322 break;
9323
9324 case Qualifiers::OCL_Autoreleasing:
9325 case Qualifiers::OCL_Weak:
9326 case Qualifiers::OCL_Strong:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009327 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00009328 << QT << EltTy.getObjCLifetime();
9329 return;
9330 }
9331 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009332 }
9333
David Blaikieb219cfc2011-09-23 05:06:16 +00009334 llvm_unreachable("found no explanation for non-trivial member");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00009335}
9336
Mike Stump1eb44332009-09-09 15:08:12 +00009337/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +00009338/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00009339static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00009340TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00009341 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009342 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +00009343 case tok::objc_private: return ObjCIvarDecl::Private;
9344 case tok::objc_public: return ObjCIvarDecl::Public;
9345 case tok::objc_protected: return ObjCIvarDecl::Protected;
9346 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00009347 }
9348}
9349
Mike Stump1eb44332009-09-09 15:08:12 +00009350/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00009351/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +00009352Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00009353 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +00009354 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009355 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +00009356
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009357 IdentifierInfo *II = D.getIdentifier();
9358 Expr *BitWidth = (Expr*)BitfieldWidth;
9359 SourceLocation Loc = DeclStart;
9360 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00009361
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009362 // FIXME: Unnamed fields can be handled in various different ways, for
9363 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +00009364
John McCallbf1a0282010-06-04 23:28:52 +00009365 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9366 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009367
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009368 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00009369 // 6.7.2.1p3, 6.7.2.1p4
Richard Smith282e7e62012-02-04 09:53:13 +00009370 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9371 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +00009372 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009373 } else {
9374 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +00009375
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009376 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +00009377
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009378 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00009379 if (T->isReferenceType()) {
9380 Diag(Loc, diag::err_ivar_reference_type);
9381 D.setInvalidType();
9382 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009383 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9384 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00009385 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00009386 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +00009387 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009388 }
Mike Stump1eb44332009-09-09 15:08:12 +00009389
Ted Kremenekb8db21d2008-07-23 18:04:17 +00009390 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +00009391 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +00009392 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9393 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009394 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00009395 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +00009396 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9397 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +00009398 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +00009399 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009400 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanian000835d2010-08-23 18:51:39 +00009401 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009402 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +00009403 EnclosingContext = IMPDecl->getClassInterface();
9404 assert(EnclosingContext && "Implementation has no class interface!");
9405 }
9406 else
9407 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00009408 } else {
9409 if (ObjCCategoryDecl *CDecl =
9410 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9411 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
9412 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +00009413 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00009414 }
9415 }
Daniel Dunbara19331f2010-04-02 18:29:09 +00009416 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00009417 }
Mike Stump1eb44332009-09-09 15:08:12 +00009418
Ted Kremenekb8db21d2008-07-23 18:04:17 +00009419 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009420 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9421 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +00009422 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +00009423
Douglas Gregor72de6672009-01-08 20:45:30 +00009424 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00009425 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +00009426 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009427 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +00009428 && !isa<TagDecl>(PrevDecl)) {
9429 Diag(Loc, diag::err_duplicate_member) << II;
9430 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9431 NewID->setInvalidDecl();
9432 }
9433 }
9434
Ted Kremenekb8db21d2008-07-23 18:04:17 +00009435 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009436 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +00009437
Chris Lattnereaaebc72009-04-25 08:06:05 +00009438 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009439 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00009440
John McCallf85e1932011-06-15 23:02:42 +00009441 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009442 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +00009443 NewID->setInvalidDecl();
9444
Douglas Gregor591dc842011-09-12 16:11:24 +00009445 if (D.getDeclSpec().isModulePrivateSpecified())
9446 NewID->setModulePrivate();
9447
Douglas Gregor72de6672009-01-08 20:45:30 +00009448 if (II) {
9449 // FIXME: When interfaces are DeclContexts, we'll need to add
9450 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +00009451 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +00009452 IdResolver.AddDecl(NewID);
9453 }
9454
John McCalld226f652010-08-21 09:40:31 +00009455 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00009456}
9457
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009458/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9459/// class and class extensions. For every class @interface and class
9460/// extension @interface, if the last ivar is a bitfield of any type,
9461/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00009462void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009463 SmallVectorImpl<Decl *> &AllIvarDecls) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009464 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9465 return;
9466
9467 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9468 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9469
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009470 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009471 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00009472 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009473 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00009474 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009475 if (!CD->IsClassExtension())
9476 return;
9477 }
9478 // No need to add this to end of @implementation.
9479 else
9480 return;
9481 }
9482 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +00009483 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9484 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009485
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00009486 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009487 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009488 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +00009489 Context.getTrivialTypeSourceInfo(Context.CharTy,
9490 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +00009491 ObjCIvarDecl::Private, BW,
9492 true);
9493 AllIvarDecls.push_back(Ivar);
9494}
9495
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00009496void Sema::ActOnFields(Scope* S,
John McCalld226f652010-08-21 09:40:31 +00009497 SourceLocation RecLoc, Decl *EnclosingDecl,
David Blaikie77b6de02011-09-22 02:58:26 +00009498 llvm::ArrayRef<Decl *> Fields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00009499 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00009500 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00009501 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +00009502
Chris Lattner1829a6d2009-02-23 22:00:08 +00009503 // If the decl this is being inserted into is invalid, then it may be a
9504 // redeclaration or some other bogus case. Don't try to add fields to it.
Douglas Gregor48822fb2011-09-12 18:58:37 +00009505 if (EnclosingDecl->isInvalidDecl())
Chris Lattner1829a6d2009-02-23 22:00:08 +00009506 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009507
Eli Friedman11e70d72012-02-07 05:00:47 +00009508 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9509
9510 // Start counting up the number of named members; make sure to include
9511 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +00009512 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +00009513 if (Record) {
9514 for (RecordDecl::decl_iterator i = Record->decls_begin(),
9515 e = Record->decls_end(); i != e; i++) {
9516 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9517 if (IFD->getDeclName())
9518 ++NumNamedMembers;
9519 }
9520 }
9521
9522 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009523 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00009524
John McCallf85e1932011-06-15 23:02:42 +00009525 bool ARCErrReported = false;
David Blaikie77b6de02011-09-22 02:58:26 +00009526 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9527 i != end; ++i) {
9528 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +00009529
Reid Spencer5f016e22007-07-11 17:01:13 +00009530 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +00009531 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00009532
Douglas Gregor72de6672009-01-08 20:45:30 +00009533 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00009534 // Remember all fields written by the user.
9535 RecFields.push_back(FD);
9536 }
Mike Stump1eb44332009-09-09 15:08:12 +00009537
Chris Lattner24793662009-03-05 22:45:59 +00009538 // If the field is already invalid for some reason, don't emit more
9539 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +00009540 if (FD->isInvalidDecl()) {
9541 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +00009542 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +00009543 }
Mike Stump1eb44332009-09-09 15:08:12 +00009544
Douglas Gregore7450f52009-03-24 19:52:54 +00009545 // C99 6.7.2.1p2:
9546 // A structure or union shall not contain a member with
9547 // incomplete or function type (hence, a structure shall not
9548 // contain an instance of itself, but may contain a pointer to
9549 // an instance of itself), except that the last member of a
9550 // structure with more than one named member may have incomplete
9551 // array type; such a structure (and any union containing,
9552 // possibly recursively, a member that is such a structure)
9553 // shall not be a member of a structure or an element of an
9554 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +00009555 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00009556 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009557 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009558 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00009559 FD->setInvalidDecl();
9560 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00009561 continue;
Francois Pichet09246182010-09-15 00:14:08 +00009562 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +00009563 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00009564 ((getLangOpts().MicrosoftExt ||
9565 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +00009566 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +00009567 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +00009568 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +00009569 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +00009570 // as the sole element of a struct/class.
David Blaikie4e4d0842012-03-11 07:00:24 +00009571 if (getLangOpts().MicrosoftExt) {
Francois Pichet09246182010-09-15 00:14:08 +00009572 if (Record->isUnion())
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +00009573 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichet09246182010-09-15 00:14:08 +00009574 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +00009575 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +00009576 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichet09246182010-09-15 00:14:08 +00009577 << FD->getDeclName() << Record->getTagKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00009578 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +00009579 if (Record->isUnion())
9580 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9581 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +00009582 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +00009583 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9584 << FD->getDeclName() << Record->getTagKind();
David Chisnall0961a012012-03-16 12:15:37 +00009585 } else if (!getLangOpts().C99) {
9586 if (Record->isUnion())
9587 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9588 << FD->getDeclName();
9589 else
9590 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
9591 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +00009592 } else if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009593 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009594 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00009595 FD->setInvalidDecl();
9596 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00009597 continue;
9598 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009599 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00009600 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009601 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +00009602 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009603 FD->setInvalidDecl();
9604 EnclosingDecl->setInvalidDecl();
9605 continue;
9606 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009607 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00009608 if (Record)
9609 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +00009610 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00009611 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +00009612 diag::err_field_incomplete)) {
9613 // Incomplete type
9614 FD->setInvalidDecl();
9615 EnclosingDecl->setInvalidDecl();
9616 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +00009617 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00009618 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9619 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00009620 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00009621 Record->setHasFlexibleArrayMember(true);
9622 } else {
9623 // If this is a struct/class and this is not the last element, reject
9624 // it. Note that GCC supports variable sized arrays in the middle of
9625 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +00009626 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +00009627 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +00009628 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +00009629 else {
9630 // We support flexible arrays at the end of structs in
9631 // other structs as an extension.
9632 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9633 << FD->getDeclName();
9634 if (Record)
9635 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00009636 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009637 }
9638 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00009639 if (Record && FDTTy->getDecl()->hasObjectMember())
9640 Record->setHasObjectMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +00009641 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00009642 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009643 Diag(FD->getLocation(), diag::err_statically_allocated_object)
9644 << FixItHint::CreateInsertion(FD->getLocation(), "*");
9645 QualType T = Context.getObjCObjectPointerType(FD->getType());
9646 FD->setType(T);
John McCallf85e1932011-06-15 23:02:42 +00009647 }
David Blaikie4e4d0842012-03-11 07:00:24 +00009648 else if (!getLangOpts().CPlusPlus) {
9649 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
John McCallf85e1932011-06-15 23:02:42 +00009650 // It's an error in ARC if a field has lifetime.
9651 // We don't want to report this in a system header, though,
9652 // so we just make the field unavailable.
9653 // FIXME: that's really not sufficient; we need to make the type
9654 // itself invalid to, say, initialize or copy.
9655 QualType T = FD->getType();
9656 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9657 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9658 SourceLocation loc = FD->getLocation();
9659 if (getSourceManager().isInSystemHeader(loc)) {
9660 if (!FD->hasAttr<UnavailableAttr>()) {
9661 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009662 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +00009663 }
9664 } else {
Fariborz Jahanianba96ffc2011-12-12 23:17:04 +00009665 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
9666 << T->isBlockPointerType();
John McCallf85e1932011-06-15 23:02:42 +00009667 }
9668 ARCErrReported = true;
9669 }
9670 }
David Blaikie4e4d0842012-03-11 07:00:24 +00009671 else if (getLangOpts().ObjC1 &&
9672 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +00009673 Record && !Record->hasObjectMember()) {
9674 if (FD->getType()->isObjCObjectPointerType() ||
9675 FD->getType().isObjCGCStrong())
9676 Record->setHasObjectMember(true);
9677 else if (Context.getAsArrayType(FD->getType())) {
9678 QualType BaseType = Context.getBaseElementType(FD->getType());
9679 if (BaseType->isRecordType() &&
9680 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9681 Record->setHasObjectMember(true);
9682 else if (BaseType->isObjCObjectPointerType() ||
9683 BaseType.isObjCGCStrong())
9684 Record->setHasObjectMember(true);
9685 }
9686 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00009687 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009688 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00009689 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00009690 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00009691 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009692
Reid Spencer5f016e22007-07-11 17:01:13 +00009693 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00009694 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00009695 bool Completed = false;
9696 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9697 if (!CXXRecord->isInvalidDecl()) {
9698 // Set access bits correctly on the directly-declared conversions.
9699 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9700 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9701 I != E; ++I)
9702 Convs->setAccess(I, (*I)->getAccess());
9703
9704 if (!CXXRecord->isDependentType()) {
John McCallf85e1932011-06-15 23:02:42 +00009705 // Objective-C Automatic Reference Counting:
9706 // If a class has a non-static data member of Objective-C pointer
9707 // type (or array thereof), it is a non-POD type and its
9708 // default constructor (if any), copy constructor, copy assignment
9709 // operator, and destructor are non-trivial.
9710 //
9711 // This rule is also handled by CXXRecordDecl::completeDefinition().
9712 // However, here we check whether this particular class is only
9713 // non-POD because of the presence of an Objective-C pointer member.
9714 // If so, objects of this type cannot be shared between code compiled
9715 // with instant objects and code compiled with manual retain/release.
David Blaikie4e4d0842012-03-11 07:00:24 +00009716 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009717 CXXRecord->hasObjectMember() &&
9718 CXXRecord->getLinkage() == ExternalLinkage) {
9719 if (CXXRecord->isPOD()) {
9720 Diag(CXXRecord->getLocation(),
9721 diag::warn_arc_non_pod_class_with_object_member)
9722 << CXXRecord;
9723 } else {
9724 // FIXME: Fix-Its would be nice here, but finding a good location
9725 // for them is going to be tricky.
9726 if (CXXRecord->hasTrivialCopyConstructor())
9727 Diag(CXXRecord->getLocation(),
9728 diag::warn_arc_trivial_member_function_with_object_member)
9729 << CXXRecord << 0;
9730 if (CXXRecord->hasTrivialCopyAssignment())
9731 Diag(CXXRecord->getLocation(),
9732 diag::warn_arc_trivial_member_function_with_object_member)
9733 << CXXRecord << 1;
9734 if (CXXRecord->hasTrivialDestructor())
9735 Diag(CXXRecord->getLocation(),
9736 diag::warn_arc_trivial_member_function_with_object_member)
9737 << CXXRecord << 2;
9738 }
9739 }
9740
Sebastian Redl0ee33912011-05-19 05:13:44 +00009741 // Adjust user-defined destructor exception spec.
David Blaikie4e4d0842012-03-11 07:00:24 +00009742 if (getLangOpts().CPlusPlus0x &&
Sebastian Redl0ee33912011-05-19 05:13:44 +00009743 CXXRecord->hasUserDeclaredDestructor())
9744 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9745
Douglas Gregor7a39dd02010-09-29 00:15:42 +00009746 // Add any implicitly-declared members to this class.
9747 AddImplicitlyDeclaredMembersToClass(CXXRecord);
9748
9749 // If we have virtual base classes, we may end up finding multiple
9750 // final overriders for a given virtual function. Check for this
9751 // problem now.
9752 if (CXXRecord->getNumVBases()) {
9753 CXXFinalOverriderMap FinalOverriders;
9754 CXXRecord->getFinalOverriders(FinalOverriders);
9755
9756 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
9757 MEnd = FinalOverriders.end();
9758 M != MEnd; ++M) {
9759 for (OverridingMethods::iterator SO = M->second.begin(),
9760 SOEnd = M->second.end();
9761 SO != SOEnd; ++SO) {
9762 assert(SO->second.size() > 0 &&
9763 "Virtual function without overridding functions?");
9764 if (SO->second.size() == 1)
9765 continue;
9766
9767 // C++ [class.virtual]p2:
9768 // In a derived class, if a virtual member function of a base
9769 // class subobject has more than one final overrider the
9770 // program is ill-formed.
9771 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9772 << (NamedDecl *)M->first << Record;
9773 Diag(M->first->getLocation(),
9774 diag::note_overridden_virtual_function);
9775 for (OverridingMethods::overriding_iterator
9776 OM = SO->second.begin(),
9777 OMEnd = SO->second.end();
9778 OM != OMEnd; ++OM)
9779 Diag(OM->Method->getLocation(), diag::note_final_overrider)
9780 << (NamedDecl *)M->first << OM->Method->getParent();
9781
9782 Record->setInvalidDecl();
9783 }
9784 }
9785 CXXRecord->completeDefinition(&FinalOverriders);
9786 Completed = true;
9787 }
9788 }
9789 }
9790 }
9791
9792 if (!Completed)
9793 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +00009794
Chris Lattnere1e79852008-02-06 00:51:33 +00009795 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +00009796 ObjCIvarDecl **ClsFields =
9797 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00009798 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +00009799 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009800 // Add ivar's to class's DeclContext.
9801 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9802 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009803 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009804 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00009805 // Must enforce the rule that ivars in the base classes may not be
9806 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +00009807 if (ID->getSuperClass())
9808 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +00009809 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +00009810 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00009811 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00009812 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9813 // Ivar declared in @implementation never belongs to the implementation.
9814 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +00009815 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00009816 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +00009817 IMPDecl->setIvarLBraceLoc(LBrac);
9818 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00009819 } else if (ObjCCategoryDecl *CDecl =
9820 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00009821 // case of ivars in class extension; all other cases have been
9822 // reported as errors elsewhere.
9823 // FIXME. Class extension does not have a LocEnd field.
9824 // CDecl->setLocEnd(RBrac);
9825 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +00009826 // Diagnose redeclaration of private ivars.
9827 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00009828 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +00009829 if (IDecl) {
9830 if (const ObjCIvarDecl *ClsIvar =
9831 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9832 Diag(ClsFields[i]->getLocation(),
9833 diag::err_duplicate_ivar_declaration);
9834 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9835 continue;
9836 }
9837 for (const ObjCCategoryDecl *ClsExtDecl =
9838 IDecl->getFirstClassExtension();
9839 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9840 if (const ObjCIvarDecl *ClsExtIvar =
9841 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9842 Diag(ClsFields[i]->getLocation(),
9843 diag::err_duplicate_ivar_declaration);
9844 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9845 continue;
9846 }
9847 }
9848 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00009849 ClsFields[i]->setLexicalDeclContext(CDecl);
9850 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00009851 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00009852 CDecl->setIvarLBraceLoc(LBrac);
9853 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00009854 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00009855 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00009856
9857 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009858 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00009859
9860 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9861 // set the visibility of this record.
9862 if (Record && !Record->getDeclContext()->isRecord())
9863 AddPushedVisibilityAttribute(Record);
Reid Spencer5f016e22007-07-11 17:01:13 +00009864}
9865
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009866/// \brief Determine whether the given integral value is representable within
9867/// the given type T.
9868static bool isRepresentableIntegerValue(ASTContext &Context,
9869 llvm::APSInt &Value,
9870 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00009871 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00009872 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009873
Douglas Gregor1274ccd2010-10-08 23:50:27 +00009874 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +00009875 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +00009876 --BitWidth;
9877 return Value.getActiveBits() <= BitWidth;
9878 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009879 return Value.getMinSignedBits() <= BitWidth;
9880}
9881
9882// \brief Given an integral type, return the next larger integral type
9883// (or a NULL type of no such type exists).
9884static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9885 // FIXME: Int128/UInt128 support, which also needs to be introduced into
9886 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00009887 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009888 const unsigned NumTypes = 4;
9889 QualType SignedIntegralTypes[NumTypes] = {
9890 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9891 };
9892 QualType UnsignedIntegralTypes[NumTypes] = {
9893 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
9894 Context.UnsignedLongLongTy
9895 };
9896
9897 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +00009898 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9899 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009900 for (unsigned I = 0; I != NumTypes; ++I)
9901 if (Context.getTypeSize(Types[I]) > BitWidth)
9902 return Types[I];
9903
9904 return QualType();
9905}
9906
Douglas Gregor879fd492009-03-17 19:05:46 +00009907EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9908 EnumConstantDecl *LastEnumConst,
9909 SourceLocation IdLoc,
9910 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +00009911 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009912 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009913 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +00009914 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +00009915
9916 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9917 Val = 0;
9918
Eli Friedman19efa3e2011-12-06 00:10:34 +00009919 if (Val)
9920 Val = DefaultLvalueConversion(Val).take();
9921
Douglas Gregor4912c342009-11-06 00:03:12 +00009922 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +00009923 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +00009924 EltTy = Context.DependentTy;
9925 else {
Douglas Gregor4912c342009-11-06 00:03:12 +00009926 SourceLocation ExpLoc;
David Blaikie4e4d0842012-03-11 07:00:24 +00009927 if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
9928 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +00009929 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
9930 // constant-expression in the enumerator-definition shall be a converted
9931 // constant expression of the underlying type.
9932 EltTy = Enum->getIntegerType();
9933 ExprResult Converted =
9934 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
9935 CCEK_Enumerator);
9936 if (Converted.isInvalid())
9937 Val = 0;
9938 else
9939 Val = Converted.take();
9940 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +00009941 !(Val = VerifyIntegerConstantExpression(Val,
9942 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +00009943 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +00009944 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00009945 if (Enum->isFixed()) {
9946 EltTy = Enum->getIntegerType();
9947
Richard Smith8ef7b202012-01-18 23:55:52 +00009948 // In Obj-C and Microsoft mode, require the enumeration value to be
9949 // representable in the underlying type of the enumeration. In C++11,
9950 // we perform a non-narrowing conversion as part of converted constant
9951 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +00009952 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009953 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +00009954 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +00009955 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +00009956 } else
9957 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +00009958 } else
John Wiegley429bb272011-04-08 18:41:53 +00009959 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00009960 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +00009961 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +00009962 // If the underlying type is not fixed, the type of each enumerator
9963 // is the type of its initializing value:
9964 // - If an initializer is specified for an enumerator, the
9965 // initializing value has the same type as the expression.
9966 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +00009967 } else {
9968 // C99 6.7.2.2p2:
9969 // The expression that defines the value of an enumeration constant
9970 // shall be an integer constant expression that has a value
9971 // representable as an int.
9972
9973 // Complain if the value is not representable in an int.
9974 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9975 Diag(IdLoc, diag::ext_enum_value_not_int)
9976 << EnumVal.toString(10) << Val->getSourceRange()
9977 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9978 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9979 // Force the type of the expression to 'int'.
9980 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9981 }
9982 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00009983 }
Douglas Gregor4912c342009-11-06 00:03:12 +00009984 }
Douglas Gregor879fd492009-03-17 19:05:46 +00009985 }
9986 }
Mike Stump1eb44332009-09-09 15:08:12 +00009987
Douglas Gregor879fd492009-03-17 19:05:46 +00009988 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +00009989 if (Enum->isDependentType())
9990 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00009991 else if (!LastEnumConst) {
9992 // C++0x [dcl.enum]p5:
9993 // If the underlying type is not fixed, the type of each enumerator
9994 // is the type of its initializing value:
9995 // - If no initializer is specified for the first enumerator, the
9996 // initializing value has an unspecified integral type.
9997 //
9998 // GCC uses 'int' for its unspecified integral type, as does
9999 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010000 if (Enum->isFixed()) {
10001 EltTy = Enum->getIntegerType();
10002 }
10003 else {
10004 EltTy = Context.IntTy;
10005 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010006 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000010007 // Assign the last value + 1.
10008 EnumVal = LastEnumConst->getInitVal();
10009 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010010 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000010011
10012 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010013 if (EnumVal < LastEnumConst->getInitVal()) {
10014 // C++0x [dcl.enum]p5:
10015 // If the underlying type is not fixed, the type of each enumerator
10016 // is the type of its initializing value:
10017 //
10018 // - Otherwise the type of the initializing value is the same as
10019 // the type of the initializing value of the preceding enumerator
10020 // unless the incremented value is not representable in that type,
10021 // in which case the type is an unspecified integral type
10022 // sufficient to contain the incremented value. If no such type
10023 // exists, the program is ill-formed.
10024 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010025 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010026 // There is no integral type larger enough to represent this
10027 // value. Complain, then allow the value to wrap around.
10028 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000010029 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010030 ++EnumVal;
10031 if (Enum->isFixed())
10032 // When the underlying type is fixed, this is ill-formed.
10033 Diag(IdLoc, diag::err_enumerator_wrapped)
10034 << EnumVal.toString(10)
10035 << EltTy;
10036 else
10037 Diag(IdLoc, diag::warn_enumerator_too_large)
10038 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010039 } else {
10040 EltTy = T;
10041 }
10042
10043 // Retrieve the last enumerator's value, extent that type to the
10044 // type that is supposed to be large enough to represent the incremented
10045 // value, then increment.
10046 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000010047 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000010048 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010049 ++EnumVal;
10050
10051 // If we're not in C++, diagnose the overflow of enumerator values,
10052 // which in C99 means that the enumerator value is not representable in
10053 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10054 // permits enumerator values that are representable in some larger
10055 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010056 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010057 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000010058 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010059 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10060 // Enforce C99 6.7.2.2p2 even when we compute the next value.
10061 Diag(IdLoc, diag::ext_enum_value_not_int)
10062 << EnumVal.toString(10) << 1;
10063 }
Douglas Gregor879fd492009-03-17 19:05:46 +000010064 }
10065 }
Mike Stump1eb44332009-09-09 15:08:12 +000010066
Douglas Gregor9b9edd62010-03-02 17:53:14 +000010067 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010068 // Make the enumerator value match the signedness and size of the
10069 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000010070 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000010071 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010072 }
Douglas Gregor4912c342009-11-06 00:03:12 +000010073
Douglas Gregor879fd492009-03-17 19:05:46 +000010074 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000010075 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000010076}
10077
10078
John McCall5b629aa2010-10-22 23:36:17 +000010079Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10080 SourceLocation IdLoc, IdentifierInfo *Id,
10081 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000010082 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000010083 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000010084 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000010085 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000010086
Chris Lattner31e05722007-08-26 06:24:45 +000010087 // The scope passed in may not be a decl scope. Zip up the scope tree until
10088 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000010089 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000010090
Reid Spencer5f016e22007-07-11 17:01:13 +000010091 // Verify that there isn't already something declared with this name in this
10092 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000010093 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000010094 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000010095 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010096 // Maybe we will complain about the shadowed template parameter.
10097 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10098 // Just pretend that we didn't see the previous declaration.
10099 PrevDecl = 0;
10100 }
10101
10102 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000010103 // When in C++, we may get a TagDecl with the same name; in this case the
10104 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000010105 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000010106 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000010107 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010108 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000010109 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000010110 else
Chris Lattner3c73c412008-11-19 08:23:25 +000010111 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010112 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000010113 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000010114 }
10115 }
10116
Douglas Gregora6e937c2010-10-15 13:21:21 +000010117 // C++ [class.mem]p13:
10118 // If T is the name of a class, then each of the following shall have a
10119 // name different from T:
10120 // - every enumerator of every member of class T that is an enumerated
10121 // type
10122 if (CXXRecordDecl *Record
10123 = dyn_cast<CXXRecordDecl>(
10124 TheEnumDecl->getDeclContext()->getRedeclContext()))
10125 if (Record->getIdentifier() && Record->getIdentifier() == Id)
10126 Diag(IdLoc, diag::err_member_name_of_class) << Id;
10127
John McCall5b629aa2010-10-22 23:36:17 +000010128 EnumConstantDecl *New =
10129 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000010130
John McCall92f88312010-01-23 00:46:32 +000010131 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000010132 // Process attributes.
10133 if (Attr) ProcessDeclAttributeList(S, New, Attr);
10134
10135 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000010136 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000010137 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000010138 }
Douglas Gregor45579f52008-12-17 02:04:30 +000010139
John McCalld226f652010-08-21 09:40:31 +000010140 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000010141}
10142
Mike Stumpc6e35aa2009-05-16 07:06:02 +000010143void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000010144 SourceLocation RBraceLoc, Decl *EnumDeclX,
10145 Decl **Elements, unsigned NumElements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010146 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000010147 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000010148 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010149
10150 if (Attr)
10151 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000010152
Eli Friedmaned0716b2009-12-11 01:34:50 +000010153 if (Enum->isDependentType()) {
10154 for (unsigned i = 0; i != NumElements; ++i) {
10155 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000010156 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000010157 if (!ECD) continue;
10158
10159 ECD->setType(EnumType);
10160 }
10161
John McCall1b5a6182010-05-06 08:49:23 +000010162 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000010163 return;
10164 }
10165
Chris Lattnere37f0be2007-08-28 05:10:31 +000010166 // TODO: If the result value doesn't fit in an int, it must be a long or long
10167 // long value. ISO C does not support this, but GCC does as an extension,
10168 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010169 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10170 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10171 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000010172
Chris Lattnerac609682007-08-28 06:15:15 +000010173 // Verify that all the values are okay, compute the size of the values, and
10174 // reverse the list.
10175 unsigned NumNegativeBits = 0;
10176 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000010177
Chris Lattnerac609682007-08-28 06:15:15 +000010178 // Keep track of whether all elements have type int.
10179 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000010180
Reid Spencer5f016e22007-07-11 17:01:13 +000010181 for (unsigned i = 0; i != NumElements; ++i) {
10182 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000010183 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000010184 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000010185
Chris Lattner211a30e2007-08-28 05:27:00 +000010186 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000010187
Chris Lattnerac609682007-08-28 06:15:15 +000010188 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000010189 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000010190 NumPositiveBits = std::max(NumPositiveBits,
10191 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000010192 else
Chris Lattner21dd8212008-01-14 21:47:29 +000010193 NumNegativeBits = std::max(NumNegativeBits,
10194 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000010195
Chris Lattnerac609682007-08-28 06:15:15 +000010196 // Keep track of whether every enum element has type int (very commmon).
10197 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000010198 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000010199 }
Mike Stump1eb44332009-09-09 15:08:12 +000010200
Chris Lattnerac609682007-08-28 06:15:15 +000010201 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000010202 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010203 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010204
John McCall842aef82009-12-09 09:09:27 +000010205 // C++0x N3000 [conv.prom]p3:
10206 // An rvalue of an unscoped enumeration type whose underlying
10207 // type is not fixed can be converted to an rvalue of the first
10208 // of the following types that can represent all the values of
10209 // the enumeration: int, unsigned int, long int, unsigned long
10210 // int, long long int, or unsigned long long int.
10211 // C99 6.4.4.3p2:
10212 // An identifier declared as an enumeration constant has type int.
10213 // The C99 rule is modified by a gcc extension
10214 QualType BestPromotionType;
10215
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010216 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000010217 // -fshort-enums is the equivalent to specifying the packed attribute on all
10218 // enum definitions.
10219 if (LangOpts.ShortEnums)
10220 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010221
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010222 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000010223 BestType = Enum->getIntegerType();
10224 if (BestType->isPromotableIntegerType())
10225 BestPromotionType = Context.getPromotedIntegerType(BestType);
10226 else
10227 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000010228 // We don't need to set BestWidth, because BestType is going to be the type
10229 // of the enumerators, but we do anyway because otherwise some compilers
10230 // warn that it might be used uninitialized.
10231 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010232 }
10233 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000010234 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000010235 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010236 // If it's packed, check also if it fits a char or a short.
10237 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000010238 BestType = Context.SignedCharTy;
10239 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000010240 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010241 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000010242 BestType = Context.ShortTy;
10243 BestWidth = ShortWidth;
10244 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000010245 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010246 BestWidth = IntWidth;
10247 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010248 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000010249
John McCall842aef82009-12-09 09:09:27 +000010250 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000010251 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000010252 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010253 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000010254
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010255 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000010256 Diag(Enum->getLocation(), diag::warn_enum_too_large);
10257 BestType = Context.LongLongTy;
10258 }
10259 }
John McCall842aef82009-12-09 09:09:27 +000010260 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000010261 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010262 // If there is no negative value, figure out the smallest type that fits
10263 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010264 // If it's packed, check also if it fits a char or a short.
10265 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000010266 BestType = Context.UnsignedCharTy;
10267 BestPromotionType = Context.IntTy;
10268 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000010269 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000010270 BestType = Context.UnsignedShortTy;
10271 BestPromotionType = Context.IntTy;
10272 BestWidth = ShortWidth;
10273 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000010274 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010275 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010276 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000010277 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010278 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010279 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010280 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000010281 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010282 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000010283 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010284 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000010285 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010286 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010287 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000010288 "How could an initializer get larger than ULL?");
10289 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010290 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000010291 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000010292 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000010293 }
10294 }
Mike Stump1eb44332009-09-09 15:08:12 +000010295
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010296 // Loop over all of the enumerator constants, changing their types to match
10297 // the type of the enum if needed.
10298 for (unsigned i = 0; i != NumElements; ++i) {
John McCalld226f652010-08-21 09:40:31 +000010299 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010300 if (!ECD) continue; // Already issued a diagnostic.
10301
10302 // Standard C says the enumerators have int type, but we allow, as an
10303 // extension, the enumerators to be larger than int size. If each
10304 // enumerator value fits in an int, type it as an int, otherwise type it the
10305 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
10306 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010307
10308 // Determine whether the value fits into an int.
10309 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010310
10311 // If it fits into an integer type, force it. Otherwise force it to match
10312 // the enum decl type.
10313 QualType NewTy;
10314 unsigned NewWidth;
10315 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000010316 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000010317 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000010318 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010319 NewTy = Context.IntTy;
10320 NewWidth = IntWidth;
10321 NewSign = true;
10322 } else if (ECD->getType() == BestType) {
10323 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000010324 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000010325 // C++ [dcl.enum]p4: Following the closing brace of an
10326 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000010327 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000010328 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010329 continue;
10330 } else {
10331 NewTy = BestType;
10332 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000010333 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010334 }
10335
10336 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000010337 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010338 InitVal.setIsSigned(NewSign);
10339 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000010340
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010341 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000010342 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000010343 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000010344 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000010345 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000010346 ECD->getInitExpr(),
10347 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000010348 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000010349 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000010350 // C++ [dcl.enum]p4: Following the closing brace of an
10351 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000010352 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000010353 ECD->setType(EnumType);
10354 else
10355 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000010356 }
Mike Stump1eb44332009-09-09 15:08:12 +000010357
John McCall1b5a6182010-05-06 08:49:23 +000010358 Enum->completeDefinition(BestType, BestPromotionType,
10359 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000010360
10361 // If we're declaring a function, ensure this decl isn't forgotten about -
10362 // it needs to go into the function scope.
10363 if (InFunctionDeclarator)
10364 DeclsInPrototypeScope.push_back(Enum);
10365
Reid Spencer5f016e22007-07-11 17:01:13 +000010366}
10367
Abramo Bagnara21e006e2011-03-03 14:20:18 +000010368Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10369 SourceLocation StartLoc,
10370 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000010371 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000010372
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000010373 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000010374 AsmString, StartLoc,
10375 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010376 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000010377 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000010378}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010379
Douglas Gregor5948ae12012-01-03 18:04:46 +000010380DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10381 SourceLocation ImportLoc,
10382 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000010383 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000010384 Module::AllVisible,
10385 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000010386 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000010387 return true;
10388
Douglas Gregor15de72c2011-12-02 23:23:56 +000010389 llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10390 Module *ModCheck = Mod;
10391 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10392 // If we've run out of module parents, just drop the remaining identifiers.
10393 // We need the length to be consistent.
10394 if (!ModCheck)
10395 break;
10396 ModCheck = ModCheck->Parent;
10397
10398 IdentifierLocs.push_back(Path[I].second);
10399 }
10400
10401 ImportDecl *Import = ImportDecl::Create(Context,
10402 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000010403 AtLoc.isValid()? AtLoc : ImportLoc,
10404 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000010405 Context.getTranslationUnitDecl()->addDecl(Import);
10406 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000010407}
10408
David Chisnall5f3c1632012-02-18 16:12:34 +000010409void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10410 IdentifierInfo* AliasName,
10411 SourceLocation PragmaLoc,
10412 SourceLocation NameLoc,
10413 SourceLocation AliasNameLoc) {
10414 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10415 LookupOrdinaryName);
10416 AsmLabelAttr *Attr =
10417 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000010418
10419 if (PrevDecl)
10420 PrevDecl->addAttr(Attr);
10421 else
10422 (void)ExtnameUndeclaredIdentifiers.insert(
10423 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10424}
10425
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010426void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10427 SourceLocation PragmaLoc,
10428 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000010429 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010430
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010431 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000010432 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000010433 } else {
10434 (void)WeakUndeclaredIdentifiers.insert(
10435 std::pair<IdentifierInfo*,WeakInfo>
10436 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010437 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010438}
10439
10440void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10441 IdentifierInfo* AliasName,
10442 SourceLocation PragmaLoc,
10443 SourceLocation NameLoc,
10444 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000010445 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10446 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000010447 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010448
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010449 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000010450 if (!PrevDecl->hasAttr<AliasAttr>())
10451 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000010452 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000010453 } else {
10454 (void)WeakUndeclaredIdentifiers.insert(
10455 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010456 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000010457}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000010458
10459Decl *Sema::getObjCDeclContext() const {
10460 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10461}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000010462
10463AvailabilityResult Sema::getCurContextAvailability() const {
10464 const Decl *D = cast<Decl>(getCurLexicalContext());
10465 // A category implicitly has the availability of the interface.
10466 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10467 D = CatD->getClassInterface();
10468
10469 return D->getAvailability();
10470}