blob: 500de928bf6dd195e2dddeaad7ad559fbda7b874 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000017#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000020#include "TypeLocBuilder.h"
Chris Lattner622c1932008-02-06 00:51:33 +000021#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000026#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000028#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000029#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000030#include "clang/AST/CharUnits.h"
John McCall8b0666c2010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000033#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000034#include "clang/Basic/PartialDiagnostic.h"
Fariborz Jahanianed1933b2011-10-03 22:11:57 +000035#include "clang/Sema/DelayedDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000036#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000037#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000038// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000039#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000040#include "clang/Lex/HeaderSearch.h"
Douglas Gregor08142532011-08-26 23:56:07 +000041#include "clang/Lex/ModuleLoader.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000042#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000043#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000044#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000045#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000046#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000047using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000048using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000049
Richard Smithcd1c0552011-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 McCall48871652010-08-21 09:40:31 +000056 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000057}
58
Kaelyn Uhrainb1378402012-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 Gregorec6e1892009-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 Gregor9817f4a2009-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 Gregorec6e1892009-02-04 19:16:12 +000091///
92/// If name lookup results in an ambiguity, this routine will complain
93/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +000094ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
95 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +000096 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +000097 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +000098 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +000099 bool WantNontrivialTypeSourceInfo,
100 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000101 // Determine where we will perform name lookup.
102 DeclContext *LookupCtx = 0;
103 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000104 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000105 if (ObjectType->isRecordType())
106 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000107 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-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 Smith23d55872012-04-02 01:30:27 +0000121 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000122 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000123
John McCallc392f372010-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 Gregor844cb502011-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 McCallba7bf592010-08-24 05:47:05 +0000130 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000131 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000132 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000133
134 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000135 }
136
John McCallba7bf592010-08-24 05:47:05 +0000137 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000138 }
139
John McCall0b66eb32010-05-01 00:40:08 +0000140 if (!LookupCtx->isDependentContext() &&
141 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000142 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000143 }
Eli Friedman9025ec22009-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 Gregora25d65d2009-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 Gregorc9f9b862009-05-11 19:58:34 +0000156
Douglas Gregora25d65d2009-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 Lattnera3778332009-02-16 22:07:16 +0000171 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000172 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000173 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000174 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000175 if (CorrectedII) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000176 TypeNameValidatorCCC Validator(true);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000177 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000178 Kind, S, SS, Validator);
Kaelyn Uhrain85308c62011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000194 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-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 Bagnara4244b432012-01-27 08:46:19 +0000199 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000200 WantNontrivialTypeSourceInfo);
201 if (Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000202 std::string CorrectedStr(Correction.getAsString(getLangOpts()));
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000203 std::string CorrectedQuotedStr(
David Blaikiebbafb8a2012-03-11 07:00:24 +0000204 Correction.getQuoted(getLangOpts()));
Kaelyn Uhrain85308c62011-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 Lattnera3778332009-02-16 22:07:16 +0000221 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000222 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000223 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000224 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000225
Chris Lattnere40853a2009-10-25 22:09:09 +0000226 case LookupResult::Ambiguous:
John McCall6538c932009-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 McCall27b18f82009-11-17 02:14:36 +0000232 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
233 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000234 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000235 }
John McCall6538c932009-10-10 05:48:19 +0000236
Douglas Gregorfe3d7d02009-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 Stump11289f42009-09-09 15:08:12 +0000241 if (!IIDecl ||
242 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000243 IIDecl->getLocation().getRawEncoding())
244 IIDecl = *Res;
Douglas Gregorfe3d7d02009-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 McCall27b18f82009-11-17 02:14:36 +0000255 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000256 return ParsedType();
Douglas Gregorfe3d7d02009-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 Gregorfe3d7d02009-04-01 21:51:26 +0000263 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000264
Chris Lattnera3778332009-02-16 22:07:16 +0000265 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000266 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000267 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000268 }
269
Chris Lattner17e15f12009-10-25 17:16:46 +0000270 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000271
Chris Lattner17e15f12009-10-25 17:16:46 +0000272 QualType T;
273 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000274 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000275
Chris Lattner17e15f12009-10-25 17:16:46 +0000276 if (T.isNull())
277 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-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 Gregor844cb502011-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 Bagnara9033e2b2012-02-06 19:09:27 +0000290 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-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 Lattner17e15f12009-10-25 17:16:46 +0000297 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000298 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000299 if (!HasTrailingDot)
300 T = Context.getObjCInterfaceType(IDecl);
301 }
302
303 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000304 // If it's not plausibly a type, suppress diagnostics.
305 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000306 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000307 }
John McCallba7bf592010-08-24 05:47:05 +0000308 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000309}
310
Chris Lattnerffaa0e62009-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 McCall27b18f82009-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 McCall67c00872009-12-02 08:25:40 +0000322 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000323 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-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 Lattnerffaa0e62009-04-12 21:49:30 +0000328 }
329 }
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000331 return DeclSpec::TST_unspecified;
332}
333
Francois Pichet48c946e2011-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 Pichet9a57fb52011-10-11 01:50:09 +0000348bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000349 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000350 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-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 Pichet9a57fb52011-10-11 01:50:09 +0000357 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000358 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000359 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000360}
361
Douglas Gregor15e56022009-10-13 23:27:22 +0000362bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
363 SourceLocation IILoc,
364 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000365 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000366 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000367 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000368 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000369
Douglas Gregor2d435302009-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 Uhrainb1378402012-01-18 21:41:41 +0000372 TypeNameValidatorCCC Validator(false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000373 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000374 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000375 Validator)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000376 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
377 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000378
Douglas Gregorc2fa1692011-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 Gregorc2fa1692011-06-28 16:20:02 +0000384 } else {
385 NamedDecl *Result = Corrected.getCorrectionDecl();
Kaelyn Uhrainb1378402012-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 Gregor2d435302009-12-30 17:04:44 +0000397
Kaelyn Uhrainb1378402012-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 Bagnara4244b432012-01-27 08:46:19 +0000403 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000404 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000405 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000406 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000407 }
408
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-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 Gregor786123d2010-05-21 23:18:07 +0000415 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000416 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000417 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000418 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-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 Gregor15e56022009-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 Gregor2d435302009-12-30 17:04:44 +0000432 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-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 Pichet48c946e2011-04-13 02:38:49 +0000438 unsigned DiagID = diag::err_typename_missing;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000439 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000440 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000441
442 Diag(SS->getRange().getBegin(), DiagID)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000443 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000444 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000445 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
David Blaikie30d15442011-10-19 22:56:21 +0000446 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
447 .get();
Douglas Gregor15e56022009-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 Lattnerffaa0e62009-04-12 21:49:30 +0000455
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000459 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-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
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000473static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
474 Scope *S, CXXScopeSpec &SS,
475 IdentifierInfo *&Name,
476 SourceLocation NameLoc) {
477 Result.clear(Sema::LookupTagName);
478 SemaRef.LookupParsedName(Result, S, &SS);
479 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
480 const char *TagName = 0;
481 const char *FixItTagName = 0;
482 switch (Tag->getTagKind()) {
483 case TTK_Class:
484 TagName = "class";
485 FixItTagName = "class ";
486 break;
487
488 case TTK_Enum:
489 TagName = "enum";
490 FixItTagName = "enum ";
491 break;
492
493 case TTK_Struct:
494 TagName = "struct";
495 FixItTagName = "struct ";
496 break;
497
498 case TTK_Union:
499 TagName = "union";
500 FixItTagName = "union ";
501 break;
502 }
503
504 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
505 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
506 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
507
508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName);
509 if (SemaRef.LookupParsedName(R, S, &SS)) {
510 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
511 I != IEnd; ++I)
512 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
513 << Name << TagName;
514 }
515 return true;
516 }
517
518 Result.clear(Sema::LookupOrdinaryName);
519 return false;
520}
521
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000522Sema::NameClassification Sema::ClassifyName(Scope *S,
523 CXXScopeSpec &SS,
524 IdentifierInfo *&Name,
525 SourceLocation NameLoc,
526 const Token &NextToken) {
527 DeclarationNameInfo NameInfo(Name, NameLoc);
528 ObjCMethodDecl *CurMethod = getCurMethodDecl();
529
530 if (NextToken.is(tok::coloncolon)) {
531 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
532 QualType(), false, SS, 0, false);
533
534 }
535
536 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
537 LookupParsedName(Result, S, &SS, !CurMethod);
538
539 // Perform lookup for Objective-C instance variables (including automatically
540 // synthesized instance variables), if we're in an Objective-C method.
541 // FIXME: This lookup really, really needs to be folded in to the normal
542 // unqualified lookup mechanism.
543 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
544 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000545 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000546 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000547 }
548
549 bool SecondTry = false;
550 bool IsFilteredTemplateName = false;
551
552Corrected:
553 switch (Result.getResultKind()) {
554 case LookupResult::NotFound:
555 // If an unqualified-id is followed by a '(', then we have a function
556 // call.
557 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
558 // In C++, this is an ADL-only call.
559 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000560 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000561 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
562
563 // C90 6.3.2.2:
564 // If the expression that precedes the parenthesized argument list in a
565 // function call consists solely of an identifier, and if no
566 // declaration is visible for this identifier, the identifier is
567 // implicitly declared exactly as if, in the innermost block containing
568 // the function call, the declaration
569 //
570 // extern int identifier ();
571 //
572 // appeared.
573 //
574 // We also allow this in C99 as an extension.
575 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
576 Result.addDecl(D);
577 Result.resolveKind();
578 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
579 }
580 }
581
582 // In C, we first see whether there is a tag type by the same name, in
583 // which case it's likely that the user just forget to write "enum",
584 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000585 if (!getLangOpts().CPlusPlus && !SecondTry &&
586 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
587 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000588 }
589
590 // Perform typo correction to determine if there is another name that is
591 // close to this name.
592 if (!SecondTry) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000593 SecondTry = true;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000594 CorrectionCandidateCallback DefaultValidator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000595 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000596 Result.getLookupKind(), S,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000597 &SS, DefaultValidator)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000598 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
599 unsigned QualifiedDiag = diag::err_no_member_suggest;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000600 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
601 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000602
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000603 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000604 NamedDecl *UnderlyingFirstDecl
605 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000606 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000607 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000608 UnqualifiedDiag = diag::err_no_template_suggest;
609 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000610 } else if (UnderlyingFirstDecl &&
611 (isa<TypeDecl>(UnderlyingFirstDecl) ||
612 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
613 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000614 UnqualifiedDiag = diag::err_unknown_typename_suggest;
615 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
616 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000617
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000618 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000619 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000620 << Name << CorrectedQuotedStr
621 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000622 else
Douglas Gregor5e16c162011-04-27 03:47:06 +0000623 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000624 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000625 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000626 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000627
628 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000629 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000630
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000631 // Typo correction corrected to a keyword.
632 if (Corrected.isKeyword())
633 return Corrected.getCorrectionAsIdentifierInfo();
634
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000635 // Also update the LookupResult...
636 // FIXME: This should probably go away at some point
637 Result.clear();
638 Result.setLookupName(Corrected.getCorrection());
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000639 if (FirstDecl) {
640 Result.addDecl(FirstDecl);
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000641 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
642 << CorrectedQuotedStr;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000643 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000644
645 // If we found an Objective-C instance variable, let
646 // LookupInObjCMethod build the appropriate expression to
647 // reference the ivar.
648 // FIXME: This is a gross hack.
649 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
650 Result.clear();
651 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
652 return move(E);
653 }
654
655 goto Corrected;
656 }
657 }
658
659 // We failed to correct; just fall through and let the parser deal with it.
660 Result.suppressDiagnostics();
661 return NameClassification::Unknown();
662
Abramo Bagnara7945c982012-01-27 09:46:47 +0000663 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000664 // We performed name lookup into the current instantiation, and there were
665 // dependent bases, so we treat this result the same way as any other
666 // dependent nested-name-specifier.
667
668 // C++ [temp.res]p2:
669 // A name used in a template declaration or definition and that is
670 // dependent on a template-parameter is assumed not to name a type
671 // unless the applicable name lookup finds a type name or the name is
672 // qualified by the keyword typename.
673 //
674 // FIXME: If the next token is '<', we might want to ask the parser to
675 // perform some heroics to see if we actually have a
676 // template-argument-list, which would indicate a missing 'template'
677 // keyword here.
Abramo Bagnara7945c982012-01-27 09:46:47 +0000678 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
679 NameInfo, /*TemplateArgs=*/0);
680 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000681
682 case LookupResult::Found:
683 case LookupResult::FoundOverloaded:
684 case LookupResult::FoundUnresolvedValue:
685 break;
686
687 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000688 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000689 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000690 // C++ [temp.local]p3:
691 // A lookup that finds an injected-class-name (10.2) can result in an
692 // ambiguity in certain cases (for example, if it is found in more than
693 // one base class). If all of the injected-class-names that are found
694 // refer to specializations of the same class template, and if the name
695 // is followed by a template-argument-list, the reference refers to the
696 // class template itself and not a specialization thereof, and is not
697 // ambiguous.
698 //
699 // This filtering can make an ambiguous result into an unambiguous one,
700 // so try again after filtering out template names.
701 FilterAcceptableTemplateNames(Result);
702 if (!Result.isAmbiguous()) {
703 IsFilteredTemplateName = true;
704 break;
705 }
706 }
707
708 // Diagnose the ambiguity and return an error.
709 return NameClassification::Error();
710 }
711
David Blaikiebbafb8a2012-03-11 07:00:24 +0000712 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000713 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
714 // C++ [temp.names]p3:
715 // After name lookup (3.4) finds that a name is a template-name or that
716 // an operator-function-id or a literal- operator-id refers to a set of
717 // overloaded functions any member of which is a function template if
718 // this is followed by a <, the < is always taken as the delimiter of a
719 // template-argument-list and never as the less-than operator.
720 if (!IsFilteredTemplateName)
721 FilterAcceptableTemplateNames(Result);
722
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000723 if (!Result.empty()) {
724 bool IsFunctionTemplate;
725 TemplateName Template;
726 if (Result.end() - Result.begin() > 1) {
727 IsFunctionTemplate = true;
728 Template = Context.getOverloadedTemplateName(Result.begin(),
729 Result.end());
730 } else {
731 TemplateDecl *TD
732 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
733 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
734
735 if (SS.isSet() && !SS.isInvalid())
736 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000737 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000738 TD);
739 else
740 Template = TemplateName(TD);
741 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000742
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000743 if (IsFunctionTemplate) {
744 // Function templates always go through overload resolution, at which
745 // point we'll perform the various checks (e.g., accessibility) we need
746 // to based on which function we selected.
747 Result.suppressDiagnostics();
748
749 return NameClassification::FunctionTemplate(Template);
750 }
751
752 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000753 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000754 }
755
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000756 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000757 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
758 DiagnoseUseOfDecl(Type, NameLoc);
759 QualType T = Context.getTypeDeclType(Type);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000760 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000761 }
762
763 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
764 if (!Class) {
765 // FIXME: It's unfortunate that we don't have a Type node for handling this.
766 if (ObjCCompatibleAliasDecl *Alias
767 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
768 Class = Alias->getClassInterface();
769 }
770
771 if (Class) {
772 DiagnoseUseOfDecl(Class, NameLoc);
773
774 if (NextToken.is(tok::period)) {
775 // Interface. <something> is parsed as a property reference expression.
776 // Just return "unknown" as a fall-through for now.
777 Result.suppressDiagnostics();
778 return NameClassification::Unknown();
779 }
780
781 QualType T = Context.getObjCInterfaceType(Class);
782 return ParsedType::make(T);
783 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000784
785 // Check for a tag type hidden by a non-type decl in a few cases where it
786 // seems likely a type is wanted instead of the non-type that was found.
787 if (!getLangOpts().ObjC1 && FirstDecl && !isa<ClassTemplateDecl>(FirstDecl) &&
788 !isa<TypeAliasTemplateDecl>(FirstDecl)) {
789 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
790 if ((NextToken.is(tok::identifier) ||
791 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
792 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
793 FirstDecl = (*Result.begin())->getUnderlyingDecl();
794 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
795 DiagnoseUseOfDecl(Type, NameLoc);
796 QualType T = Context.getTypeDeclType(Type);
797 return ParsedType::make(T);
798 }
799 }
800 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000801
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000802 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000803 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000804
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000805 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
806 return BuildDeclarationNameExpr(SS, Result, ADL);
807}
808
John McCall5ed6e8f2009-08-18 00:00:49 +0000809// Determines the context to return to after temporarily entering a
810// context. This depends in an unnecessarily complicated way on the
811// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000812DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000813
John McCall5ed6e8f2009-08-18 00:00:49 +0000814 // Functions defined inline within classes aren't parsed until we've
815 // finished parsing the top-level class, so the top-level class is
816 // the context we'll need to return to.
817 if (isa<FunctionDecl>(DC)) {
818 DC = DC->getLexicalParent();
819
820 // A function not defined within a class will always return to its
821 // lexical context.
822 if (!isa<CXXRecordDecl>(DC))
823 return DC;
824
825 // A C++ inline method/friend is parsed *after* the topmost class
826 // it was declared in is fully parsed ("complete"); the topmost
827 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000828 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000829 DC = RD;
830
831 // Return the declaration context of the topmost class the inline method is
832 // declared in.
833 return DC;
834 }
835
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000836 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000837}
838
Douglas Gregor91f84212008-12-11 16:49:14 +0000839void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000840 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000841 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000842 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000843 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000844}
845
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000846void Sema::PopDeclContext() {
847 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000848
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000849 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000850 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000851}
852
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000853/// EnterDeclaratorContext - Used when we must lookup names in the context
854/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000855///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000856void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000857 // C++0x [basic.lookup.unqual]p13:
858 // A name used in the definition of a static data member of class
859 // X (after the qualified-id of the static member) is looked up as
860 // if the name was used in a member function of X.
861 // C++0x [basic.lookup.unqual]p14:
862 // If a variable member of a namespace is defined outside of the
863 // scope of its namespace then any name used in the definition of
864 // the variable member (after the declarator-id) is looked up as
865 // if the definition of the variable member occurred in its
866 // namespace.
867 // Both of these imply that we should push a scope whose context
868 // is the semantic context of the declaration. We can't use
869 // PushDeclContext here because that context is not necessarily
870 // lexically contained in the current context. Fortunately,
871 // the containing scope should have the appropriate information.
872
873 assert(!S->getEntity() && "scope already has entity");
874
875#ifndef NDEBUG
876 Scope *Ancestor = S->getParent();
877 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
878 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
879#endif
880
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000881 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000882 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000883}
884
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000885void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000886 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000887
John McCall6df5fef2009-12-19 10:49:29 +0000888 // Switch back to the lexical context. The safety of this is
889 // enforced by an assert in EnterDeclaratorContext.
890 Scope *Ancestor = S->getParent();
891 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
892 CurContext = (DeclContext*) Ancestor->getEntity();
893
894 // We don't need to do anything with the scope, which is going to
895 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000896}
897
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000898
899void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
900 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
901 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
902 // We assume that the caller has already called
903 // ActOnReenterTemplateScope
904 FD = TFD->getTemplatedDecl();
905 }
906 if (!FD)
907 return;
908
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000909 // Same implementation as PushDeclContext, but enters the context
910 // from the lexical parent, rather than the top-level class.
911 assert(CurContext == FD->getLexicalParent() &&
912 "The next DeclContext should be lexically contained in the current one.");
913 CurContext = FD;
914 S->setEntity(CurContext);
915
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000916 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
917 ParmVarDecl *Param = FD->getParamDecl(P);
918 // If the parameter has an identifier, then add it to the scope
919 if (Param->getIdentifier()) {
920 S->AddDecl(Param);
921 IdResolver.AddDecl(Param);
922 }
923 }
924}
925
926
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000927void Sema::ActOnExitFunctionContext() {
928 // Same implementation as PopDeclContext, but returns to the lexical parent,
929 // rather than the top-level class.
930 assert(CurContext && "DeclContext imbalance!");
931 CurContext = CurContext->getLexicalParent();
932 assert(CurContext && "Popped translation unit!");
933}
934
935
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000936/// \brief Determine whether we allow overloading of the function
937/// PrevDecl with another declaration.
938///
939/// This routine determines whether overloading is possible, not
940/// whether some new function is actually an overload. It will return
941/// true in C++ (where we can always provide overloads) or, as an
942/// extension, in C when the previous function is already an
943/// overloaded function declaration or has the "overloadable"
944/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000945static bool AllowOverloadingOfFunction(LookupResult &Previous,
946 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000947 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000948 return true;
949
John McCall1f82f242009-11-18 22:49:29 +0000950 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000951 return true;
952
John McCall1f82f242009-11-18 22:49:29 +0000953 return (Previous.getResultKind() == LookupResult::Found
954 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000955}
956
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000957/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000958void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000959 // Move up the scope chain until we find the nearest enclosing
960 // non-transparent context. The declaration will be introduced into this
961 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000962 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000963 ((DeclContext *)S->getEntity())->isTransparentContext())
964 S = S->getParent();
965
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000966 // Add scoped declarations into their context, so that they can be
967 // found later. Declarations without a context won't be inserted
968 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000969 if (AddToContext)
970 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000971
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000972 // Out-of-line definitions shouldn't be pushed into scope in C++.
973 // Out-of-line variable and function definitions shouldn't even in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000974 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
Douglas Gregorf7b98952011-10-09 22:57:49 +0000975 D->isOutOfLine() &&
976 !D->getDeclContext()->getRedeclContext()->Equals(
977 D->getLexicalDeclContext()->getRedeclContext()))
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000978 return;
979
980 // Template instantiations should also not be pushed into scope.
981 if (isa<FunctionDecl>(D) &&
982 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000983 return;
984
John McCall9f3059a2009-10-09 21:13:30 +0000985 // If this replaces anything in the current scope,
986 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
987 IEnd = IdResolver.end();
988 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +0000989 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
990 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +0000991 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000992
John McCall9f3059a2009-10-09 21:13:30 +0000993 // Should only need to replace one decl.
994 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000995 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000996 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000997
John McCall48871652010-08-21 09:40:31 +0000998 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000999
1000 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1001 // Implicitly-generated labels may end up getting generated in an order that
1002 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1003 // the label at the appropriate place in the identifier chain.
1004 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001005 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001006 if (IDC == CurContext) {
1007 if (!S->isDeclScope(*I))
1008 continue;
1009 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001010 break;
1011 }
1012
Douglas Gregor46c04e72011-03-16 16:39:03 +00001013 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001014 } else {
1015 IdResolver.AddDecl(D);
1016 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001017}
1018
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001019void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1020 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1021 TUScope->AddDecl(D);
1022}
1023
Douglas Gregordb446112011-03-07 16:54:27 +00001024bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1025 bool ExplicitInstantiationOrSpecialization) {
1026 return IdResolver.isDeclInScope(D, Ctx, Context, S,
1027 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +00001028}
1029
John McCallcc14d1f2010-08-24 08:50:51 +00001030Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1031 DeclContext *TargetDC = DC->getPrimaryContext();
1032 do {
1033 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1034 if (ScopeDC->getPrimaryContext() == TargetDC)
1035 return S;
1036 } while ((S = S->getParent()));
1037
1038 return 0;
1039}
1040
John McCall1f82f242009-11-18 22:49:29 +00001041static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1042 DeclContext*,
1043 ASTContext&);
1044
1045/// Filters out lookup results that don't fall within the given scope
1046/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00001047void Sema::FilterLookupForScope(LookupResult &R,
1048 DeclContext *Ctx, Scope *S,
1049 bool ConsiderLinkage,
1050 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +00001051 LookupResult::Filter F = R.makeFilter();
1052 while (F.hasNext()) {
1053 NamedDecl *D = F.next();
1054
Richard Smith3f1b5d02011-05-05 21:57:07 +00001055 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +00001056 continue;
1057
1058 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00001059 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001060 continue;
1061
1062 F.erase();
1063 }
1064
1065 F.done();
1066}
1067
1068static bool isUsingDecl(NamedDecl *D) {
1069 return isa<UsingShadowDecl>(D) ||
1070 isa<UnresolvedUsingTypenameDecl>(D) ||
1071 isa<UnresolvedUsingValueDecl>(D);
1072}
1073
1074/// Removes using shadow declarations from the lookup results.
1075static void RemoveUsingDecls(LookupResult &R) {
1076 LookupResult::Filter F = R.makeFilter();
1077 while (F.hasNext())
1078 if (isUsingDecl(F.next()))
1079 F.erase();
1080
1081 F.done();
1082}
1083
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001084/// \brief Check for this common pattern:
1085/// @code
1086/// class S {
1087/// S(const S&); // DO NOT IMPLEMENT
1088/// void operator=(const S&); // DO NOT IMPLEMENT
1089/// };
1090/// @endcode
1091static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1092 // FIXME: Should check for private access too but access is set after we get
1093 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001094 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001095 return false;
1096
1097 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1098 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001099 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1100 return Method->isCopyAssignmentOperator();
1101 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001102}
1103
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001104bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1105 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001106
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001107 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1108 return false;
1109
1110 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001111 if (D->getDeclContext()->isDependentContext() ||
1112 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001113 return false;
1114
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001115 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001116 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1117 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001118
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001119 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1120 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1121 return false;
1122 } else {
1123 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +00001124 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001125 FD->isInlineSpecified())
1126 return false;
1127 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001128
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001129 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001130 Context.DeclMustBeEmitted(FD))
1131 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001132 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1133 if (!VD->isFileVarDecl() ||
1134 VD->getType().isConstant(Context) ||
1135 Context.DeclMustBeEmitted(VD))
1136 return false;
1137
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001138 if (VD->isStaticDataMember() &&
1139 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1140 return false;
1141
John McCalld37d35b2010-10-27 01:41:35 +00001142 } else {
1143 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001144 }
1145
John McCalld37d35b2010-10-27 01:41:35 +00001146 // Only warn for unused decls internal to the translation unit.
1147 if (D->getLinkage() == ExternalLinkage)
1148 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001149
John McCalld37d35b2010-10-27 01:41:35 +00001150 return true;
1151}
1152
1153void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001154 if (!D)
1155 return;
1156
1157 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1158 const FunctionDecl *First = FD->getFirstDeclaration();
1159 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1160 return; // First should already be in the vector.
1161 }
1162
1163 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1164 const VarDecl *First = VD->getFirstDeclaration();
1165 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1166 return; // First should already be in the vector.
1167 }
1168
1169 if (ShouldWarnIfUnusedFileScopedDecl(D))
1170 UnusedFileScopedDecls.push_back(D);
1171 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001172
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001173static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001174 if (D->isInvalidDecl())
1175 return false;
1176
Eli Friedmanc09e0552012-01-13 23:41:25 +00001177 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001178 return false;
John McCall67da35c2010-02-04 22:26:26 +00001179
Chris Lattnercab02a62011-02-17 20:34:02 +00001180 if (isa<LabelDecl>(D))
1181 return true;
1182
John McCall67da35c2010-02-04 22:26:26 +00001183 // White-list anything that isn't a local variable.
1184 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1185 !D->getDeclContext()->isFunctionOrMethod())
1186 return false;
1187
1188 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001189 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001190
1191 // White-list anything with an __attribute__((unused)) type.
1192 QualType Ty = VD->getType();
1193
1194 // Only look at the outermost level of typedef.
1195 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1196 if (TT->getDecl()->hasAttr<UnusedAttr>())
1197 return false;
1198 }
1199
Douglas Gregor14f232e2010-05-08 23:05:03 +00001200 // If we failed to complete the type for some reason, or if the type is
1201 // dependent, don't diagnose the variable.
1202 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001203 return false;
1204
John McCallcef15822010-03-31 02:47:45 +00001205 if (const TagType *TT = Ty->getAs<TagType>()) {
1206 const TagDecl *Tag = TT->getDecl();
1207 if (Tag->hasAttr<UnusedAttr>())
1208 return false;
1209
1210 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Rafael Espindola7c23b082012-01-06 04:54:01 +00001211 if (!RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001212 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001213
1214 if (const Expr *Init = VD->getInit()) {
1215 const CXXConstructExpr *Construct =
1216 dyn_cast<CXXConstructExpr>(Init);
1217 if (Construct && !Construct->isElidable()) {
1218 CXXConstructorDecl *CD = Construct->getConstructor();
1219 if (!CD->isTrivial())
1220 return false;
1221 }
1222 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001223 }
1224 }
John McCallcef15822010-03-31 02:47:45 +00001225
1226 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001227 }
1228
John McCall67da35c2010-02-04 22:26:26 +00001229 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001230}
1231
Anna Zaks964f4c62011-07-28 20:52:06 +00001232static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1233 FixItHint &Hint) {
1234 if (isa<LabelDecl>(D)) {
1235 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001236 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001237 if (AfterColon.isInvalid())
1238 return;
1239 Hint = FixItHint::CreateRemoval(CharSourceRange::
1240 getCharRange(D->getLocStart(), AfterColon));
1241 }
1242 return;
1243}
1244
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001245/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1246/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001247void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001248 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001249 if (!ShouldDiagnoseUnusedDecl(D))
1250 return;
1251
Anna Zaks964f4c62011-07-28 20:52:06 +00001252 GenerateFixForUnusedDecl(D, Context, Hint);
1253
Chris Lattnercab02a62011-02-17 20:34:02 +00001254 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001255 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001256 DiagID = diag::warn_unused_exception_param;
1257 else if (isa<LabelDecl>(D))
1258 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001259 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001260 DiagID = diag::warn_unused_variable;
1261
Anna Zaks964f4c62011-07-28 20:52:06 +00001262 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001263}
1264
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001265static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1266 // Verify that we have no forward references left. If so, there was a goto
1267 // or address of a label taken, but no definition of it. Label fwd
1268 // definitions are indicated with a null substmt.
1269 if (L->getStmt() == 0)
1270 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1271}
1272
Steve Naroffc62adb62007-10-09 22:01:59 +00001273void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001274 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001275 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001276 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001277
Chris Lattner302b4be2006-11-19 02:31:38 +00001278 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1279 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001280 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001281 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001282
Douglas Gregor91f84212008-12-11 16:49:14 +00001283 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1284 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001285
Douglas Gregor91f84212008-12-11 16:49:14 +00001286 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001287
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001288 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001289 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001290 DiagnoseUnusedDecl(D);
1291
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001292 // If this was a forward reference to a label, verify it was defined.
1293 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1294 CheckPoppedLabel(LD, *this);
1295
Douglas Gregor91f84212008-12-11 16:49:14 +00001296 // Remove this name from our lexical scope.
1297 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001298 }
1299}
1300
James Molloy6f8780b2012-02-29 10:24:19 +00001301void Sema::ActOnStartFunctionDeclarator() {
1302 ++InFunctionDeclarator;
1303}
1304
1305void Sema::ActOnEndFunctionDeclarator() {
1306 assert(InFunctionDeclarator);
1307 --InFunctionDeclarator;
1308}
1309
Douglas Gregor1c283312010-08-11 12:19:30 +00001310/// \brief Look for an Objective-C class in the translation unit.
1311///
1312/// \param Id The name of the Objective-C class we're looking for. If
1313/// typo-correction fixes this name, the Id will be updated
1314/// to the fixed name.
1315///
1316/// \param IdLoc The location of the name in the translation unit.
1317///
1318/// \param TypoCorrection If true, this routine will attempt typo correction
1319/// if there is no class with the given name.
1320///
1321/// \returns The declaration of the named Objective-C class, or NULL if the
1322/// class could not be found.
1323ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1324 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001325 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001326 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1327 // creation from this context.
1328 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1329
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001330 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001331 // Perform typo correction at the given location, but only if we
1332 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001333 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1334 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1335 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001336 Validator)) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001337 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001338 Diag(IdLoc, diag::err_undef_interface_suggest)
1339 << Id << IDecl->getDeclName()
1340 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1341 Diag(IDecl->getLocation(), diag::note_previous_decl)
1342 << IDecl->getDeclName();
1343
1344 Id = IDecl->getIdentifier();
1345 }
1346 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001347 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1348 // This routine must always return a class definition, if any.
1349 if (Def && Def->getDefinition())
1350 Def = Def->getDefinition();
1351 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001352}
1353
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001354/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1355/// from S, where a non-field would be declared. This routine copes
1356/// with the difference between C and C++ scoping rules in structs and
1357/// unions. For example, the following code is well-formed in C but
1358/// ill-formed in C++:
1359/// @code
1360/// struct S6 {
1361/// enum { BAR } e;
1362/// };
Mike Stump11289f42009-09-09 15:08:12 +00001363///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001364/// void test_S6() {
1365/// struct S6 a;
1366/// a.e = BAR;
1367/// }
1368/// @endcode
1369/// For the declaration of BAR, this routine will return a different
1370/// scope. The scope S will be the scope of the unnamed enumeration
1371/// within S6. In C++, this routine will return the scope associated
1372/// with S6, because the enumeration's scope is a transparent
1373/// context but structures can contain non-field names. In C, this
1374/// routine will return the translation unit scope, since the
1375/// enumeration's scope is a transparent context and structures cannot
1376/// contain non-field names.
1377Scope *Sema::getNonFieldDeclScope(Scope *S) {
1378 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001379 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001380 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001381 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001382 S = S->getParent();
1383 return S;
1384}
1385
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001386/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1387/// file scope. lazily create a decl for it. ForRedeclaration is true
1388/// if we're creating this built-in in anticipation of redeclaring the
1389/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001390NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001391 Scope *S, bool ForRedeclaration,
1392 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001393 Builtin::ID BID = (Builtin::ID)bid;
1394
Chris Lattnerecd79c62009-06-14 00:45:47 +00001395 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001396 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001397 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001398 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001399 // Okay
1400 break;
1401
Mike Stump93246cc2009-07-28 23:57:15 +00001402 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001403 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001404 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001405 << Context.BuiltinInfo.GetName(BID);
1406 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001407
Mike Stump93246cc2009-07-28 23:57:15 +00001408 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001409 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001410 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001411 << Context.BuiltinInfo.GetName(BID);
1412 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001413
1414 case ASTContext::GE_Missing_ucontext:
1415 if (ForRedeclaration)
1416 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1417 << Context.BuiltinInfo.GetName(BID);
1418 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001419 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001420
1421 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1422 Diag(Loc, diag::ext_implicit_lib_function_decl)
1423 << Context.BuiltinInfo.GetName(BID)
1424 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001425 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001426 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001427 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001428 Diag(Loc, diag::note_please_include_header)
1429 << Context.BuiltinInfo.getHeaderName(BID)
1430 << Context.BuiltinInfo.GetName(BID);
1431 }
1432
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001433 FunctionDecl *New = FunctionDecl::Create(Context,
1434 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001435 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001436 SC_Extern,
1437 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001438 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001439 New->setImplicit();
1440
Chris Lattner4dd27102008-05-05 22:18:14 +00001441 // Create Decl objects for each parameter, adding them to the
1442 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001443 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001444 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001445 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1446 ParmVarDecl *parm =
1447 ParmVarDecl::Create(Context, New, SourceLocation(),
1448 SourceLocation(), 0,
1449 FT->getArgType(i), /*TInfo=*/0,
1450 SC_None, SC_None, 0);
1451 parm->setScopeInfo(0, i);
1452 Params.push_back(parm);
1453 }
David Blaikie9c70e042011-09-21 18:16:56 +00001454 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
1457 AddKnownFunctionAttributes(New);
1458
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001459 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001460 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1461 // relate Scopes to DeclContexts, and probably eliminate CurContext
1462 // entirely, but we're not there yet.
1463 DeclContext *SavedContext = CurContext;
1464 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001465 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001466 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001467 return New;
1468}
1469
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001470bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1471 QualType OldType;
1472 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1473 OldType = OldTypedef->getUnderlyingType();
1474 else
1475 OldType = Context.getTypeDeclType(Old);
1476 QualType NewType = New->getUnderlyingType();
1477
Douglas Gregoraab36982012-01-11 22:33:48 +00001478 if (NewType->isVariablyModifiedType()) {
1479 // Must not redefine a typedef with a variably-modified type.
1480 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1481 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1482 << Kind << NewType;
1483 if (Old->getLocation().isValid())
1484 Diag(Old->getLocation(), diag::note_previous_definition);
1485 New->setInvalidDecl();
1486 return true;
1487 }
1488
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001489 if (OldType != NewType &&
1490 !OldType->isDependentType() &&
1491 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001492 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001493 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1494 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1495 << Kind << NewType << OldType;
1496 if (Old->getLocation().isValid())
1497 Diag(Old->getLocation(), diag::note_previous_definition);
1498 New->setInvalidDecl();
1499 return true;
1500 }
1501 return false;
1502}
1503
Richard Smithdda56e42011-04-15 14:24:37 +00001504/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001505/// same name and scope as a previous declaration 'Old'. Figure out
1506/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001507/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001508///
Richard Smithdda56e42011-04-15 14:24:37 +00001509void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001510 // If the new decl is known invalid already, don't bother doing any
1511 // merging checks.
1512 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001513
Steve Naroff44cfcb62008-09-09 14:32:20 +00001514 // Allow multiple definitions for ObjC built-in typedefs.
1515 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001516 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001517 const IdentifierInfo *TypeID = New->getIdentifier();
1518 switch (TypeID->getLength()) {
1519 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001520 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +00001521 if (!TypeID->isStr("id"))
1522 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001523 Context.setObjCIdRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001524 // Install the built-in type for 'id', ignoring the current definition.
1525 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1526 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001527 case 5:
1528 if (!TypeID->isStr("Class"))
1529 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001530 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001531 // Install the built-in type for 'Class', ignoring the current definition.
1532 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001533 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001534 case 3:
1535 if (!TypeID->isStr("SEL"))
1536 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001537 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001538 // Install the built-in type for 'SEL', ignoring the current definition.
1539 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001540 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001541 }
1542 // Fall through - the typedef name was not a builtin type.
1543 }
John McCall1f82f242009-11-18 22:49:29 +00001544
Douglas Gregorfb034662009-01-28 17:15:10 +00001545 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001546 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1547 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001548 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001549 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001550
1551 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001552 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001553 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001554
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001555 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001556 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001557
John McCall1f82f242009-11-18 22:49:29 +00001558 // If the old declaration is invalid, just give up here.
1559 if (Old->isInvalidDecl())
1560 return New->setInvalidDecl();
1561
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001562 // If the typedef types are not identical, reject them in all languages and
1563 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001564 if (isIncompatibleTypedef(Old, New))
1565 return;
Mike Stump11289f42009-09-09 15:08:12 +00001566
John McCall91f1a022009-12-30 00:31:22 +00001567 // The types match. Link up the redeclaration chain if the old
1568 // declaration was a typedef.
Richard Smithdda56e42011-04-15 14:24:37 +00001569 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1570 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001571
David Blaikiebbafb8a2012-03-11 07:00:24 +00001572 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001573 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001574
David Blaikiebbafb8a2012-03-11 07:00:24 +00001575 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001576 // C++ [dcl.typedef]p2:
1577 // In a given non-class scope, a typedef specifier can be used to
1578 // redefine the name of any type declared in that scope to refer
1579 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001580 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001581 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001582
1583 // C++0x [dcl.typedef]p4:
1584 // In a given class scope, a typedef specifier can be used to redefine
1585 // any class-name declared in that scope that is not also a typedef-name
1586 // to refer to the type to which it already refers.
1587 //
1588 // This wording came in via DR424, which was a correction to the
1589 // wording in DR56, which accidentally banned code like:
1590 //
1591 // struct S {
1592 // typedef struct A { } A;
1593 // };
1594 //
1595 // in the C++03 standard. We implement the C++0x semantics, which
1596 // allow the above but disallow
1597 //
1598 // struct S {
1599 // typedef int I;
1600 // typedef int I;
1601 // };
1602 //
1603 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001604 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001605 return;
1606
Chris Lattner2581fc32009-04-17 22:04:20 +00001607 Diag(New->getLocation(), diag::err_redefinition)
1608 << New->getDeclName();
1609 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001610 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001611 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001612
Douglas Gregor7363fb02012-01-11 04:25:01 +00001613 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001614 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001615 return;
1616
Chris Lattner2581fc32009-04-17 22:04:20 +00001617 // If we have a redefinition of a typedef in C, emit a warning. This warning
1618 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001619 // -Wtypedef-redefinition. If either the original or the redefinition is
1620 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001621 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001622 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1623 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001624 return;
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattner2581fc32009-04-17 22:04:20 +00001626 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1627 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001628 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001629 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001630}
1631
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001632/// DeclhasAttr - returns true if decl Declaration already has the target
1633/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001634static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001635DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001636 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1637 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1638 // responsible for making sure they are consistent.
1639 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1640 if (AA)
1641 return false;
1642
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001643 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001644 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001645 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1646 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001647 if (Ann) {
1648 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1649 return true;
1650 continue;
1651 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001652 // FIXME: Don't hardcode this check
1653 if (OA && isa<OwnershipAttr>(*i))
1654 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001655 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001656 }
Chris Lattner84966392008-03-03 03:28:21 +00001657
1658 return false;
1659}
1660
John McCallf79e87d2011-03-02 04:00:57 +00001661/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Douglas Gregor32c17572012-01-01 20:30:41 +00001662void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1663 bool MergeDeprecation) {
1664 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001665 return;
John McCallf79e87d2011-03-02 04:00:57 +00001666
Douglas Gregor32c17572012-01-01 20:30:41 +00001667 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00001668
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001669 // Ensure that any moving of objects within the allocated map is done before
1670 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00001671 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00001672
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001673 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00001674 i = Old->specific_attr_begin<InheritableAttr>(),
1675 e = Old->specific_attr_end<InheritableAttr>();
1676 i != e; ++i) {
Douglas Gregorb1fa1482011-09-23 20:23:42 +00001677 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor32c17572012-01-01 20:30:41 +00001678 if (!MergeDeprecation &&
Douglas Gregorb1fa1482011-09-23 20:23:42 +00001679 (isa<DeprecatedAttr>(*i) ||
1680 isa<UnavailableAttr>(*i) ||
1681 isa<AvailabilityAttr>(*i)))
John McCalld2930c22011-07-22 02:45:48 +00001682 continue;
1683
Douglas Gregor32c17572012-01-01 20:30:41 +00001684 if (!DeclHasAttr(New, *i)) {
1685 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
John McCallf79e87d2011-03-02 04:00:57 +00001686 newAttr->setInherited(true);
Douglas Gregor32c17572012-01-01 20:30:41 +00001687 New->addAttr(newAttr);
John McCallf79e87d2011-03-02 04:00:57 +00001688 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001689 }
1690 }
John McCallf79e87d2011-03-02 04:00:57 +00001691
Douglas Gregor32c17572012-01-01 20:30:41 +00001692 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00001693}
1694
1695/// mergeParamDeclAttributes - Copy attributes from the old parameter
1696/// to the new one.
1697static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1698 const ParmVarDecl *oldDecl,
1699 ASTContext &C) {
1700 if (!oldDecl->hasAttrs())
1701 return;
1702
1703 bool foundAny = newDecl->hasAttrs();
1704
1705 // Ensure that any moving of objects within the allocated map is
1706 // done before we process them.
1707 if (!foundAny) newDecl->setAttrs(AttrVec());
1708
1709 for (specific_attr_iterator<InheritableParamAttr>
1710 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1711 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1712 if (!DeclHasAttr(newDecl, *i)) {
1713 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1714 newAttr->setInherited(true);
1715 newDecl->addAttr(newAttr);
1716 foundAny = true;
1717 }
1718 }
1719
1720 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001721}
1722
Dan Gohman28ade552010-07-26 21:25:24 +00001723namespace {
1724
Douglas Gregora74a2972009-03-06 22:43:54 +00001725/// Used in MergeFunctionDecl to keep track of function parameters in
1726/// C.
1727struct GNUCompatibleParamWarning {
1728 ParmVarDecl *OldParm;
1729 ParmVarDecl *NewParm;
1730 QualType PromotedType;
1731};
1732
Dan Gohman28ade552010-07-26 21:25:24 +00001733}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001734
1735/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001736Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001737 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001738 if (Ctor->isDefaultConstructor())
1739 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001740
1741 if (Ctor->isCopyConstructor())
1742 return Sema::CXXCopyConstructor;
1743
1744 if (Ctor->isMoveConstructor())
1745 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001746 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001747 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001748 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001749 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00001750 } else if (MD->isMoveAssignmentOperator()) {
1751 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001752 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001753
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001754 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001755}
1756
Sebastian Redl243d9052010-06-09 21:17:41 +00001757/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001758/// only extern inline functions can be redefined, and even then only in
1759/// GNU89 mode.
1760static bool canRedefineFunction(const FunctionDecl *FD,
1761 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001762 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1763 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001764 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001765 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001766}
1767
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001768/// MergeFunctionDecl - We just parsed a function 'New' from
1769/// declarator D which has the same name and scope as a previous
1770/// declaration 'Old'. Figure out how to resolve this situation,
1771/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001772///
1773/// In C++, New and Old must be declarations that are not
1774/// overloaded. Use IsOverload to determine whether New and Old are
1775/// overloaded, and to select the Old declaration that New should be
1776/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001777///
1778/// Returns true if there was an error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +00001779bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001780 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001781 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001782 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001783 = dyn_cast<FunctionTemplateDecl>(OldD))
1784 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001785 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001786 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001787 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001788 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1789 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1790 Diag(Shadow->getTargetDecl()->getLocation(),
1791 diag::note_using_decl_target);
1792 Diag(Shadow->getUsingDecl()->getLocation(),
1793 diag::note_using_decl) << 0;
1794 return true;
1795 }
1796
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001797 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001798 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001799 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001800 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001801 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001802
1803 // Determine whether the previous declaration was a definition,
1804 // implicit declaration, or a declaration.
1805 diag::kind PrevDiag;
1806 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001807 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001808 else if (Old->isImplicit())
1809 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001810 else
Chris Lattner0369c572008-11-23 23:12:31 +00001811 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001813 QualType OldQType = Context.getCanonicalType(Old->getType());
1814 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001815
Charles Davisfea48452010-02-18 02:00:42 +00001816 // Don't complain about this if we're in GNU89 mode and the old function
1817 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001818 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001819 New->getStorageClass() == SC_Static &&
1820 Old->getStorageClass() != SC_Static &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001821 !canRedefineFunction(Old, getLangOpts())) {
1822 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00001823 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1824 Diag(Old->getLocation(), PrevDiag);
1825 } else {
1826 Diag(New->getLocation(), diag::err_static_non_static) << New;
1827 Diag(Old->getLocation(), PrevDiag);
1828 return true;
1829 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00001830 }
1831
John McCallcddbad02010-02-04 05:44:44 +00001832 // If a function is first declared with a calling convention, but is
1833 // later declared or defined without one, the second decl assumes the
1834 // calling convention of the first.
1835 //
1836 // For the new decl, we have to look at the NON-canonical type to tell the
1837 // difference between a function that really doesn't have a calling
1838 // convention and one that is declared cdecl. That's because in
1839 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1840 // because it is the default calling convention.
1841 //
1842 // Note also that we DO NOT return at this point, because we still have
1843 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001844 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001845 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001846 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1847 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1848 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001849 if (OldTypeInfo.getCC() != CC_Default &&
1850 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001851 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1852 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001853 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1854 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001855 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001856 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001857 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1858 << (OldTypeInfo.getCC() == CC_Default)
1859 << (OldTypeInfo.getCC() == CC_Default ? "" :
1860 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001861 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001862 return true;
1863 }
1864
John McCallab26cfa2010-02-05 21:31:56 +00001865 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001866 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1867 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1868 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001869 }
1870
Douglas Gregor77e274f2010-06-18 21:30:25 +00001871 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00001872 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1873 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1874 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001875 Diag(New->getLocation(), diag::err_regparm_mismatch)
1876 << NewType->getRegParmType()
1877 << OldType->getRegParmType();
1878 Diag(Old->getLocation(), diag::note_previous_declaration);
1879 return true;
1880 }
John McCall4f5019e2010-12-19 02:44:49 +00001881
1882 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1883 RequiresAdjustment = true;
1884 }
1885
Douglas Gregorf1404d72011-10-14 15:55:40 +00001886 // Merge ns_returns_retained attribute.
1887 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1888 if (NewTypeInfo.getProducesResult()) {
1889 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1890 Diag(Old->getLocation(), diag::note_previous_declaration);
1891 return true;
1892 }
1893
1894 NewTypeInfo = NewTypeInfo.withProducesResult(true);
1895 RequiresAdjustment = true;
1896 }
1897
John McCall4f5019e2010-12-19 02:44:49 +00001898 if (RequiresAdjustment) {
1899 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1900 New->setType(QualType(NewType, 0));
1901 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00001902 }
1903
David Blaikiebbafb8a2012-03-11 07:00:24 +00001904 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001905 // (C++98 13.1p2):
1906 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001907 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001908 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00001909 QualType OldReturnType = OldType->getResultType();
1910 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001911 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001912 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001913 if (NewReturnType->isObjCObjectPointerType()
1914 && OldReturnType->isObjCObjectPointerType())
1915 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1916 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00001917 if (New->isCXXClassMember() && New->isOutOfLine())
1918 Diag(New->getLocation(),
1919 diag::err_member_def_does_not_match_ret_type) << New;
1920 else
1921 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001922 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1923 return true;
1924 }
1925 else
1926 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927 }
1928
1929 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001930 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001931 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001932 // Preserve triviality.
1933 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00001934
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001935 // MSVC allows explicit template specialization at class scope:
1936 // 2 CXMethodDecls referring to the same function will be injected.
1937 // We don't want a redeclartion error.
1938 bool IsClassScopeExplicitSpecialization =
1939 OldMethod->isFunctionTemplateSpecialization() &&
1940 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00001941 bool isFriend = NewMethod->getFriendObjectKind();
1942
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001943 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1944 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001945 // -- Member function declarations with the same name and the
1946 // same parameter types cannot be overloaded if any of them
1947 // is a static member function declaration.
1948 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1949 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1950 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1951 return true;
1952 }
1953
1954 // C++ [class.mem]p1:
1955 // [...] A member shall not be declared twice in the
1956 // member-specification, except that a nested class or member
1957 // class template can be declared and then later defined.
1958 unsigned NewDiag;
1959 if (isa<CXXConstructorDecl>(OldMethod))
1960 NewDiag = diag::err_constructor_redeclared;
1961 else if (isa<CXXDestructorDecl>(NewMethod))
1962 NewDiag = diag::err_destructor_redeclared;
1963 else if (isa<CXXConversionDecl>(NewMethod))
1964 NewDiag = diag::err_conv_function_redeclared;
1965 else
1966 NewDiag = diag::err_member_redeclared;
1967
1968 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001969 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001970
1971 // Complain if this is an explicit declaration of a special
1972 // member that was initially declared implicitly.
1973 //
1974 // As an exception, it's okay to befriend such methods in order
1975 // to permit the implicit constructor/destructor/operator calls.
1976 } else if (OldMethod->isImplicit()) {
1977 if (isFriend) {
1978 NewMethod->setImplicit();
1979 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001980 Diag(NewMethod->getLocation(),
1981 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001982 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001983 return true;
1984 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00001985 } else if (OldMethod->isExplicitlyDefaulted()) {
1986 Diag(NewMethod->getLocation(),
1987 diag::err_definition_of_explicitly_defaulted_member)
1988 << getSpecialMember(OldMethod);
1989 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001990 }
1991 }
1992
1993 // (C++98 8.3.5p3):
1994 // All declarations for a function shall agree exactly in both the
1995 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00001996 // We also want to respect all the extended bits except noreturn.
1997
1998 // noreturn should now match unless the old type info didn't have it.
1999 QualType OldQTypeForComparison = OldQType;
2000 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2001 assert(OldQType == QualType(OldType, 0));
2002 const FunctionType *OldTypeForComparison
2003 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2004 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2005 assert(OldQTypeForComparison.isCanonical());
2006 }
2007
2008 if (OldQTypeForComparison == NewQType)
James Molloye9430032012-03-13 08:55:35 +00002009 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010
2011 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002012 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002013
2014 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002015 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002016 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002017 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002018 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2019 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002020 const FunctionProtoType *OldProto = 0;
2021 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002022 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002023 // The old declaration provided a function prototype, but the
2024 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002025 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002026 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002027 OldProto->arg_type_end());
2028 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00002029 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00002030 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002031 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002032 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002033
2034 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002035 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002036 for (FunctionProtoType::arg_type_iterator
2037 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002038 ParamEnd = OldProto->arg_type_end();
2039 ParamType != ParamEnd; ++ParamType) {
2040 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002041 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002042 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002043 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00002044 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002045 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002046 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002047 Param->setImplicit();
2048 Params.push_back(Param);
2049 }
2050
David Blaikie9c70e042011-09-21 18:16:56 +00002051 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002052 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002053
James Molloye9430032012-03-13 08:55:35 +00002054 return MergeCompatibleFunctionDecls(New, Old, S);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002055 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002056
Douglas Gregora74a2972009-03-06 22:43:54 +00002057 // GNU C permits a K&R definition to follow a prototype declaration
2058 // if the declared types of the parameters in the K&R definition
2059 // match the types in the prototype declaration, even when the
2060 // promoted types of the parameters from the K&R definition differ
2061 // from the types in the prototype. GCC then keeps the types from
2062 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002063 //
2064 // If a variadic prototype is followed by a non-variadic K&R definition,
2065 // the K&R definition becomes variadic. This is sort of an edge case, but
2066 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2067 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002068 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002069 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002070 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002071 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002072 SmallVector<QualType, 16> ArgTypes;
2073 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002074 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002075 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002076 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002077 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002078
Douglas Gregora74a2972009-03-06 22:43:54 +00002079 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002080 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2081 NewProto->getResultType());
2082 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002083 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002084 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002085 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2086 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002087 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002088 NewProto->getArgType(Idx))) {
2089 ArgTypes.push_back(NewParm->getType());
2090 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002091 NewParm->getType(),
2092 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002093 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002094 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2095 Warnings.push_back(Warn);
2096 ArgTypes.push_back(NewParm->getType());
2097 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002098 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002099 }
2100
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002101 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002102 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2103 Diag(Warnings[Warn].NewParm->getLocation(),
2104 diag::ext_param_promoted_not_compatible_with_prototype)
2105 << Warnings[Warn].PromotedType
2106 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002107 if (Warnings[Warn].OldParm->getLocation().isValid())
2108 Diag(Warnings[Warn].OldParm->getLocation(),
2109 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002110 }
2111
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002112 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2113 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00002114 OldProto->getExtProtoInfo()));
James Molloye9430032012-03-13 08:55:35 +00002115 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregora74a2972009-03-06 22:43:54 +00002116 }
2117
2118 // Fall through to diagnose conflicting types.
2119 }
2120
Steve Naroff17832a42008-01-16 15:01:34 +00002121 // A function that has already been declared has been redeclared or defined
2122 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00002123 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002124 // The user has declared a builtin function with an incompatible
2125 // signature.
2126 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2127 // The function the user is redeclaring is a library-defined
2128 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00002129 // redeclaration, then pretend that we don't know about this
2130 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002131 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2132 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2133 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00002134 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2135 Old->setInvalidDecl();
2136 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002137 }
Steve Naroff17832a42008-01-16 15:01:34 +00002138
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002139 PrevDiag = diag::note_previous_builtin_declaration;
2140 }
2141
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002142 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002143 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002144 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002145}
2146
Douglas Gregore62c0a42009-02-24 01:23:02 +00002147/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002148/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002149///
2150/// This routine handles the merging of attributes and other
2151/// properties of function declarations form the old declaration to
2152/// the new declaration, once we know that New is in fact a
2153/// redeclaration of Old.
2154///
2155/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002156bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2157 Scope *S) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002158 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002159 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002160
2161 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00002162 if (Old->getStorageClass() != SC_Extern &&
2163 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002164 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00002165
Douglas Gregore62c0a42009-02-24 01:23:02 +00002166 // Merge "pure" flag.
2167 if (Old->isPure())
2168 New->setPure();
2169
John McCallf79e87d2011-03-02 04:00:57 +00002170 // Merge attributes from the parameters. These can mismatch with K&R
2171 // declarations.
2172 if (New->getNumParams() == Old->getNumParams())
2173 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2174 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2175 Context);
2176
David Blaikiebbafb8a2012-03-11 07:00:24 +00002177 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002178 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002179
2180 return false;
2181}
2182
John McCall31168b02011-06-15 23:02:42 +00002183
John McCallf79e87d2011-03-02 04:00:57 +00002184void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002185 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002186 // We don't want to merge unavailable and deprecated attributes
2187 // except from interface to implementation.
2188 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2189
John McCallf79e87d2011-03-02 04:00:57 +00002190 // Merge the attributes.
Douglas Gregor32c17572012-01-01 20:30:41 +00002191 mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
John McCallf79e87d2011-03-02 04:00:57 +00002192
2193 // Merge attributes from the parameters.
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002194 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2195 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002196 ni = newMethod->param_begin(), ne = newMethod->param_end();
2197 ni != ne; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00002198 mergeParamDeclAttributes(*ni, *oi, Context);
John McCalld2930c22011-07-22 02:45:48 +00002199
Douglas Gregor33823722011-06-11 01:09:30 +00002200 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00002201}
2202
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002203/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2204/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002205/// emitting diagnostics as appropriate.
2206///
2207/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002208/// to here in AddInitializerToDecl. We can't check them before the initializer
2209/// is attached.
Richard Smith30482bc2011-02-20 03:19:35 +00002210void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2211 if (New->isInvalidDecl() || Old->isInvalidDecl())
2212 return;
2213
2214 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002215 if (getLangOpts().CPlusPlus) {
Richard Smith30482bc2011-02-20 03:19:35 +00002216 AutoType *AT = New->getType()->getContainedAutoType();
2217 if (AT && !AT->isDeduced()) {
2218 // We don't know what the new type is until the initializer is attached.
2219 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002220 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2221 // These could still be something that needs exception specs checked.
2222 return MergeVarDeclExceptionSpecs(New, Old);
2223 }
Richard Smith30482bc2011-02-20 03:19:35 +00002224 // C++ [basic.link]p10:
2225 // [...] the types specified by all declarations referring to a given
2226 // object or function shall be identical, except that declarations for an
2227 // array object can specify array types that differ by the presence or
2228 // absence of a major array bound (8.3.4).
2229 else if (Old->getType()->isIncompleteArrayType() &&
2230 New->getType()->isArrayType()) {
2231 CanQual<ArrayType> OldArray
2232 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2233 CanQual<ArrayType> NewArray
2234 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2235 if (OldArray->getElementType() == NewArray->getElementType())
2236 MergedT = New->getType();
2237 } else if (Old->getType()->isArrayType() &&
2238 New->getType()->isIncompleteArrayType()) {
2239 CanQual<ArrayType> OldArray
2240 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2241 CanQual<ArrayType> NewArray
2242 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2243 if (OldArray->getElementType() == NewArray->getElementType())
2244 MergedT = Old->getType();
2245 } else if (New->getType()->isObjCObjectPointerType()
2246 && Old->getType()->isObjCObjectPointerType()) {
2247 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2248 Old->getType());
2249 }
2250 } else {
2251 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2252 }
2253 if (MergedT.isNull()) {
2254 Diag(New->getLocation(), diag::err_redefinition_different_type)
2255 << New->getDeclName();
2256 Diag(Old->getLocation(), diag::note_previous_definition);
2257 return New->setInvalidDecl();
2258 }
2259 New->setType(MergedT);
2260}
2261
Chris Lattner01564d92007-01-27 19:27:06 +00002262/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2263/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2264/// situation, merging decls or emitting diagnostics as appropriate.
2265///
Mike Stump11289f42009-09-09 15:08:12 +00002266/// Tentative definition rules (C99 6.9.2p2) are checked by
2267/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002268/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002269///
John McCall1f82f242009-11-18 22:49:29 +00002270void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2271 // If the new decl is already invalid, don't do any other checking.
2272 if (New->isInvalidDecl())
2273 return;
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chris Lattnerc511efb2007-01-27 19:32:14 +00002275 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002276 VarDecl *Old = 0;
2277 if (!Previous.isSingleResult() ||
2278 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002279 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002280 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002281 Diag(Previous.getRepresentativeDecl()->getLocation(),
2282 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002283 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002284 }
Chris Lattner84966392008-03-03 03:28:21 +00002285
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002286 // C++ [class.mem]p1:
2287 // A member shall not be declared twice in the member-specification [...]
2288 //
2289 // Here, we need only consider static data members.
2290 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2291 Diag(New->getLocation(), diag::err_duplicate_member)
2292 << New->getIdentifier();
2293 Diag(Old->getLocation(), diag::note_previous_declaration);
2294 New->setInvalidDecl();
2295 }
2296
Douglas Gregor32c17572012-01-01 20:30:41 +00002297 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00002298 // Warn if an already-declared variable is made a weak_import in a subsequent
2299 // declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002300 if (New->getAttr<WeakImportAttr>() &&
2301 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002302 !Old->getAttr<WeakImportAttr>()) {
2303 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2304 Diag(Old->getLocation(), diag::note_previous_definition);
2305 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002306 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002307 }
Chris Lattner84966392008-03-03 03:28:21 +00002308
Richard Smith30482bc2011-02-20 03:19:35 +00002309 // Merge the types.
2310 MergeVarDeclTypes(New, Old);
2311 if (New->isInvalidDecl())
2312 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002313
Steve Naroff1e787362008-01-30 00:44:01 +00002314 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002315 if (New->getStorageClass() == SC_Static &&
2316 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002317 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002318 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002319 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002320 }
Mike Stump11289f42009-09-09 15:08:12 +00002321 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002322 // For an identifier declared with the storage-class specifier
2323 // extern in a scope in which a prior declaration of that
2324 // identifier is visible,23) if the prior declaration specifies
2325 // internal or external linkage, the linkage of the identifier at
2326 // the later declaration is the same as the linkage specified at
2327 // the prior declaration. If no prior declaration is visible, or
2328 // if the prior declaration specifies no linkage, then the
2329 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002330 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002331 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002332 else if (New->getStorageClass() != SC_Static &&
2333 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002334 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002335 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002336 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002337 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002338
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002339 // Check if extern is followed by non-extern and vice-versa.
2340 if (New->hasExternalStorage() &&
2341 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2342 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2343 Diag(Old->getLocation(), diag::note_previous_definition);
2344 return New->setInvalidDecl();
2345 }
2346 if (Old->hasExternalStorage() &&
2347 !New->hasLinkage() && New->isLocalVarDecl()) {
2348 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2349 Diag(Old->getLocation(), diag::note_previous_definition);
2350 return New->setInvalidDecl();
2351 }
2352
Steve Naroffa5629372008-09-17 14:05:40 +00002353 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002354
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002355 // FIXME: The test for external storage here seems wrong? We still
2356 // need to check for mismatches.
2357 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002358 // Don't complain about out-of-line definitions of static members.
2359 !(Old->getLexicalDeclContext()->isRecord() &&
2360 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002361 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002362 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002363 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002364 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002365
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002366 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2367 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2368 Diag(Old->getLocation(), diag::note_previous_definition);
2369 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2370 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2371 Diag(Old->getLocation(), diag::note_previous_definition);
2372 }
2373
Sebastian Redlf1842912010-02-02 18:35:11 +00002374 // C++ doesn't have tentative definitions, so go right ahead and check here.
2375 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002376 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00002377 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002378 (Def = Old->getDefinition())) {
2379 Diag(New->getLocation(), diag::err_redefinition)
2380 << New->getDeclName();
2381 Diag(Def->getLocation(), diag::note_previous_definition);
2382 New->setInvalidDecl();
2383 return;
2384 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002385 // c99 6.2.2 P4.
2386 // For an identifier declared with the storage-class specifier extern in a
2387 // scope in which a prior declaration of that identifier is visible, if
2388 // the prior declaration specifies internal or external linkage, the linkage
2389 // of the identifier at the later declaration is the same as the linkage
2390 // specified at the prior declaration.
2391 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002392 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002393 Old->getLinkage() == InternalLinkage &&
2394 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002395 New->setStorageClass(Old->getStorageClass());
2396
Douglas Gregor0760fa12009-03-10 23:43:53 +00002397 // Keep a chain of previous declarations.
2398 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002399
2400 // Inherit access appropriately.
2401 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002402}
2403
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002404/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2405/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002406Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002407 DeclSpec &DS) {
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002408 return ParsedFreeStandingDeclSpec(S, AS, DS,
2409 MultiTemplateParamsArg(*this, 0, 0));
2410}
2411
2412/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2413/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2414/// parameters to cope with template friend declarations.
2415Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2416 DeclSpec &DS,
2417 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002418 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002419 TagDecl *Tag = 0;
2420 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2421 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2422 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002423 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002424 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002425
2426 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002427 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002428
John McCall07e91c02009-08-06 02:15:43 +00002429 // Note that the above type specs guarantee that the
2430 // type rep is a Decl, whereas in many of the others
2431 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00002432 if (isa<TagDecl>(TagD))
2433 Tag = cast<TagDecl>(TagD);
2434 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2435 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002436 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002437
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00002438 if (Tag) {
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00002439 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00002440 if (Tag->isInvalidDecl())
2441 return Tag;
2442 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00002443
Nuno Lopese9823fa2009-12-17 11:35:26 +00002444 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2445 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2446 // or incomplete types shall not be restrict-qualified."
2447 if (TypeQuals & DeclSpec::TQ_restrict)
2448 Diag(DS.getRestrictSpecLoc(),
2449 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2450 << DS.getSourceRange();
2451 }
2452
Richard Smitha77a0a62011-08-15 21:04:07 +00002453 if (DS.isConstexprSpecified()) {
2454 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2455 // and definitions of functions and variables.
2456 if (Tag)
2457 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2458 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2459 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2460 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2461 else
2462 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2463 // Don't emit warnings after this error.
2464 return TagD;
2465 }
2466
Douglas Gregor3dad8422009-09-26 06:47:28 +00002467 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002468 // If we're dealing with a decl but not a TagDecl, assume that
2469 // whatever routines created it handled the friendship aspect.
2470 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002471 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002472 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002473 }
John McCallaa017372011-03-22 23:00:04 +00002474
2475 // Track whether we warned about the fact that there aren't any
2476 // declarators.
2477 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002478
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002479 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00002480 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002481 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002482 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002483 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002484 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002485
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002486 Diag(DS.getLocStart(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002487 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002488 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002489 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002490 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002491
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002492 // Check for Microsoft C extension: anonymous struct.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002493 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002494 CurContext->isRecord() &&
2495 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2496 // Handle 2 kinds of anonymous struct:
2497 // struct STRUCT;
2498 // and
2499 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2500 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00002501 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002502 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2503 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002504 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002505 << DS.getSourceRange();
2506 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2507 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002508 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002509
David Blaikiebbafb8a2012-03-11 07:00:24 +00002510 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002511 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2512 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2513 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002514 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002515 Diag(Enum->getLocation(), diag::ext_no_declarators)
2516 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002517 emittedWarning = true;
2518 }
2519
2520 // Skip all the checks below if we have a type error.
2521 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002522
John McCallaa017372011-03-22 23:00:04 +00002523 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002524 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002525 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002526 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2527 Tag && isa<EnumDecl>(Tag)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002528 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002529 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002530 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002531 }
2532
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002533 Diag(DS.getLocStart(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002534 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002535 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002536 }
Mike Stump11289f42009-09-09 15:08:12 +00002537
John McCallaa017372011-03-22 23:00:04 +00002538 // We're going to complain about a bunch of spurious specifiers;
2539 // only do this if we're declaring a tag, because otherwise we
2540 // should be getting diag::ext_no_declarators.
2541 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2542 return TagD;
2543
John McCall4d55f5a2011-03-26 02:09:52 +00002544 // Note that a linkage-specification sets a storage class, but
2545 // 'extern "C" struct foo;' is actually valid and not theoretically
2546 // useless.
John McCallaa017372011-03-22 23:00:04 +00002547 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002548 if (!DS.isExternInLinkageSpec())
2549 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2550 << DeclSpec::getSpecifierName(scs);
2551
John McCallaa017372011-03-22 23:00:04 +00002552 if (DS.isThreadSpecified())
2553 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2554 if (DS.getTypeQualifiers()) {
2555 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2556 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2557 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2558 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2559 // Restrict is covered above.
2560 }
2561 if (DS.isInlineSpecified())
2562 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2563 if (DS.isVirtualSpecified())
2564 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2565 if (DS.isExplicitSpecified())
2566 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2567
Douglas Gregor41866812011-09-12 18:37:38 +00002568 if (DS.isModulePrivateSpecified() &&
2569 Tag && Tag->getDeclContext()->isFunctionOrMethod())
2570 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2571 << Tag->getTagKind()
2572 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2573
Eli Friedmane3217952011-12-17 00:36:09 +00002574 // Warn about ignored type attributes, for example:
2575 // __attribute__((aligned)) struct A;
2576 // Attributes should be placed after tag to apply to type declaration.
2577 if (!DS.getAttributes().empty()) {
2578 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2579 if (TypeSpecType == DeclSpec::TST_class ||
2580 TypeSpecType == DeclSpec::TST_struct ||
2581 TypeSpecType == DeclSpec::TST_union ||
2582 TypeSpecType == DeclSpec::TST_enum) {
2583 AttributeList* attrs = DS.getAttributes().getList();
2584 while (attrs) {
2585 Diag(attrs->getScopeLoc(),
2586 diag::warn_declspec_attribute_ignored)
2587 << attrs->getName()
2588 << (TypeSpecType == DeclSpec::TST_class ? 0 :
2589 TypeSpecType == DeclSpec::TST_struct ? 1 :
2590 TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2591 attrs = attrs->getNext();
2592 }
2593 }
2594 }
John McCallaa017372011-03-22 23:00:04 +00002595
John McCall48871652010-08-21 09:40:31 +00002596 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002597}
2598
John McCallea305ed2009-12-18 10:40:03 +00002599/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002600/// check if there's an existing declaration that can't be overloaded.
2601///
2602/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002603static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2604 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002605 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002606 DeclarationName Name,
2607 SourceLocation NameLoc,
2608 unsigned diagnostic) {
2609 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2610 Sema::ForRedeclaration);
2611 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002612
John McCallea305ed2009-12-18 10:40:03 +00002613 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002614 return false;
2615
2616 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002617 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002618 assert(PrevDecl && "Expected a non-null Decl");
2619
2620 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2621 return false;
John McCall1f82f242009-11-18 22:49:29 +00002622
John McCallea305ed2009-12-18 10:40:03 +00002623 SemaRef.Diag(NameLoc, diagnostic) << Name;
2624 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002625
2626 return true;
2627}
2628
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002629/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2630/// anonymous struct or union AnonRecord into the owning context Owner
2631/// and scope S. This routine will be invoked just after we realize
2632/// that an unnamed union or struct is actually an anonymous union or
2633/// struct, e.g.,
2634///
2635/// @code
2636/// union {
2637/// int i;
2638/// float f;
2639/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2640/// // f into the surrounding scope.x
2641/// @endcode
2642///
2643/// This routine is recursive, injecting the names of nested anonymous
2644/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002645static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2646 DeclContext *Owner,
2647 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002648 AccessSpecifier AS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002649 SmallVector<NamedDecl*, 2> &Chaining,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002650 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002651 unsigned diagKind
2652 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2653 : diag::err_anonymous_struct_member_redecl;
2654
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002655 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002656
2657 // Look every FieldDecl and IndirectFieldDecl with a name.
2658 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2659 DEnd = AnonRecord->decls_end();
2660 D != DEnd; ++D) {
2661 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2662 cast<NamedDecl>(*D)->getDeclName()) {
2663 ValueDecl *VD = cast<ValueDecl>(*D);
2664 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2665 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002666 // C++ [class.union]p2:
2667 // The names of the members of an anonymous union shall be
2668 // distinct from the names of any other entity in the
2669 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002670 Invalid = true;
2671 } else {
2672 // C++ [class.union]p2:
2673 // For the purpose of name lookup, after the anonymous union
2674 // definition, the members of the anonymous union are
2675 // considered to have been defined in the scope in which the
2676 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002677 unsigned OldChainingSize = Chaining.size();
2678 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2679 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2680 PE = IF->chain_end(); PI != PE; ++PI)
2681 Chaining.push_back(*PI);
2682 else
2683 Chaining.push_back(VD);
2684
Francois Pichet783dd6e2010-11-21 06:08:52 +00002685 assert(Chaining.size() >= 2);
2686 NamedDecl **NamedChain =
2687 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2688 for (unsigned i = 0; i < Chaining.size(); i++)
2689 NamedChain[i] = Chaining[i];
2690
2691 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002692 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2693 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002694 NamedChain, Chaining.size());
2695
2696 IndirectField->setAccess(AS);
2697 IndirectField->setImplicit();
2698 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002699
2700 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002701 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002702
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002703 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002704 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002705 }
2706 }
2707
2708 return Invalid;
2709}
2710
Douglas Gregorc4df4072010-04-19 22:54:31 +00002711/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2712/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002713/// illegal input values are mapped to SC_None.
2714static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002715StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002716 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002717 case DeclSpec::SCS_unspecified: return SC_None;
2718 case DeclSpec::SCS_extern: return SC_Extern;
2719 case DeclSpec::SCS_static: return SC_Static;
2720 case DeclSpec::SCS_auto: return SC_Auto;
2721 case DeclSpec::SCS_register: return SC_Register;
2722 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002723 // Illegal SCSs map to None: error reporting is up to the caller.
2724 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002725 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002726 }
2727 llvm_unreachable("unknown storage class specifier");
2728}
2729
2730/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002731/// a StorageClass. Any error reporting is up to the caller:
2732/// illegal input values are mapped to SC_None.
2733static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002734StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002735 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002736 case DeclSpec::SCS_unspecified: return SC_None;
2737 case DeclSpec::SCS_extern: return SC_Extern;
2738 case DeclSpec::SCS_static: return SC_Static;
2739 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002740 // Illegal SCSs map to None: error reporting is up to the caller.
2741 case DeclSpec::SCS_auto: // Fall through.
2742 case DeclSpec::SCS_mutable: // Fall through.
2743 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002744 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002745 }
2746 llvm_unreachable("unknown storage class specifier");
2747}
2748
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002749/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002750/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002751/// (C++ [class.union]) and a C11 feature; anonymous structures
2752/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002753Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2754 AccessSpecifier AS,
2755 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002756 DeclContext *Owner = Record->getDeclContext();
2757
2758 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002759 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002760 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002761 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002762 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002763 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002764 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002766 // C and C++ require different kinds of checks for anonymous
2767 // structs/unions.
2768 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002769 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002770 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002771 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00002772 if (Record->isUnion()) {
2773 // C++ [class.union]p6:
2774 // Anonymous unions declared in a named namespace or in the
2775 // global namespace shall be declared static.
2776 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2777 (isa<TranslationUnitDecl>(Owner) ||
2778 (isa<NamespaceDecl>(Owner) &&
2779 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00002780 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2781 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00002782
2783 // Recover by adding 'static'.
2784 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2785 PrevSpec, DiagID);
2786 }
2787 // C++ [class.union]p6:
2788 // A storage class is not allowed in a declaration of an
2789 // anonymous union in a class scope.
2790 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2791 isa<RecordDecl>(Owner)) {
2792 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00002793 diag::err_anonymous_union_with_storage_spec)
2794 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00002795
2796 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00002797 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
2798 SourceLocation(),
David Blaikie0a8e8992011-10-19 22:43:29 +00002799 PrevSpec, DiagID);
2800 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002801 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002802
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002803 // Ignore const/volatile/restrict qualifiers.
2804 if (DS.getTypeQualifiers()) {
2805 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2806 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2807 << Record->isUnion() << 0
2808 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2809 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
David Blaikie30d15442011-10-19 22:56:21 +00002810 Diag(DS.getVolatileSpecLoc(),
2811 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002812 << Record->isUnion() << 1
2813 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2814 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
David Blaikie30d15442011-10-19 22:56:21 +00002815 Diag(DS.getRestrictSpecLoc(),
2816 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002817 << Record->isUnion() << 2
2818 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2819
2820 DS.ClearTypeQualifiers();
2821 }
2822
Mike Stump11289f42009-09-09 15:08:12 +00002823 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002824 // The member-specification of an anonymous union shall only
2825 // define non-static data members. [Note: nested types and
2826 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002827 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2828 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002829 Mem != MemEnd; ++Mem) {
2830 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2831 // C++ [class.union]p3:
2832 // An anonymous union shall not have private or protected
2833 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002834 assert(FD->getAccess() != AS_none);
2835 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002836 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2837 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2838 Invalid = true;
2839 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002840
Alexis Hunt97ab5542011-05-16 22:41:40 +00002841 // C++ [class.union]p1
2842 // An object of a class with a non-trivial constructor, a non-trivial
2843 // copy constructor, a non-trivial destructor, or a non-trivial copy
2844 // assignment operator cannot be a member of a union, nor can an
2845 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00002846 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002847 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002848 } else if ((*Mem)->isImplicit()) {
2849 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002850 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2851 // This is a type that showed up in an
2852 // elaborated-type-specifier inside the anonymous struct or
2853 // union, but which actually declares a type outside of the
2854 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002855 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2856 if (!MemRecord->isAnonymousStructOrUnion() &&
2857 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002858 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002859 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00002860 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2861 << (int)Record->isUnion();
2862 else {
2863 // This is a nested type declaration.
2864 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2865 << (int)Record->isUnion();
2866 Invalid = true;
2867 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002868 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002869 } else if (isa<AccessSpecDecl>(*Mem)) {
2870 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002871 } else {
2872 // We have something that isn't a non-static data
2873 // member. Complain about it.
2874 unsigned DK = diag::err_anonymous_record_bad_member;
2875 if (isa<TypeDecl>(*Mem))
2876 DK = diag::err_anonymous_record_with_type;
2877 else if (isa<FunctionDecl>(*Mem))
2878 DK = diag::err_anonymous_record_with_function;
2879 else if (isa<VarDecl>(*Mem))
2880 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002881
2882 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002883 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00002884 DK == diag::err_anonymous_record_with_type)
2885 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002886 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00002887 else {
2888 Diag((*Mem)->getLocation(), DK)
2889 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002890 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002891 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002892 }
2893 }
Mike Stump11289f42009-09-09 15:08:12 +00002894 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002895
2896 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002897 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002898 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002899 Invalid = true;
2900 }
2901
John McCallfa2d6922009-10-22 23:31:08 +00002902 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00002903 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00002904 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00002905 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00002906
Mike Stump11289f42009-09-09 15:08:12 +00002907 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002908 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002909 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002910 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002911 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002912 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002913 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002914 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00002915 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002916 /*BitWidth=*/0, /*Mutable=*/false,
2917 /*HasInit=*/false);
John McCallb54367d2010-05-21 20:45:30 +00002918 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002919 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002920 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002921 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002922 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2923 assert(SCSpec != DeclSpec::SCS_typedef &&
2924 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002925 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00002926 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002927 // mutable can only appear on non-static class members, so it's always
2928 // an error here
2929 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2930 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00002931 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002932 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002933 SCSpec = DS.getStorageClassSpecAsWritten();
2934 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002935 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002936
Abramo Bagnaradff19302011-03-08 08:55:46 +00002937 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002938 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002939 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002940 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002941 TInfo, SC, SCAsWritten);
Richard Smith40372352011-09-18 00:06:34 +00002942
2943 // Default-initialize the implicit variable. This initialization will be
2944 // trivial in almost all cases, except if a union member has an in-class
2945 // initializer:
2946 // union { int n = 0; };
2947 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002948 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002949 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002950
2951 // Add the anonymous struct/union object to the current
2952 // context. We'll be referencing this object when we refer to one of
2953 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002954 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00002955
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002956 // Inject the members of the anonymous struct/union into the owning
2957 // context and into the identifier resolver chain for name lookup
2958 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002959 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00002960 Chain.push_back(Anon);
2961
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002962 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2963 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002964 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002965
2966 // Mark this as an anonymous struct/union type. Note that we do not
2967 // do this until after we have already checked and injected the
2968 // members of this anonymous struct/union type, because otherwise
2969 // the members could be injected twice: once by DeclContext when it
2970 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00002971 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002972 Record->setAnonymousStructOrUnion(true);
2973
2974 if (Invalid)
2975 Anon->setInvalidDecl();
2976
John McCall48871652010-08-21 09:40:31 +00002977 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002978}
2979
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002980/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2981/// Microsoft C anonymous structure.
2982/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2983/// Example:
2984///
2985/// struct A { int a; };
2986/// struct B { struct A; int b; };
2987///
2988/// void foo() {
2989/// B var;
2990/// var.a = 3;
2991/// }
2992///
2993Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2994 RecordDecl *Record) {
2995
2996 // If there is no Record, get the record via the typedef.
2997 if (!Record)
2998 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2999
3000 // Mock up a declarator.
3001 Declarator Dc(DS, Declarator::TypeNameContext);
3002 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3003 assert(TInfo && "couldn't build declarator info for anonymous struct");
3004
3005 // Create a declaration for this anonymous struct.
3006 NamedDecl* Anon = FieldDecl::Create(Context,
3007 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003008 DS.getLocStart(),
3009 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003010 /*IdentifierInfo=*/0,
3011 Context.getTypeDeclType(Record),
3012 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003013 /*BitWidth=*/0, /*Mutable=*/false,
3014 /*HasInit=*/false);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003015 Anon->setImplicit();
3016
3017 // Add the anonymous struct object to the current context.
3018 CurContext->addDecl(Anon);
3019
3020 // Inject the members of the anonymous struct into the current
3021 // context and into the identifier resolver chain for name lookup
3022 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003023 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003024 Chain.push_back(Anon);
3025
Nico Weberf8bb3de2012-02-01 00:41:00 +00003026 RecordDecl *RecordDef = Record->getDefinition();
3027 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3028 RecordDef, AS_none,
3029 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003030 Anon->setInvalidDecl();
3031
3032 return Anon;
3033}
Steve Naroff2fea1392007-09-02 02:04:30 +00003034
Douglas Gregor92751d42008-11-17 22:58:34 +00003035/// GetNameForDeclarator - Determine the full declaration name for the
3036/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003037DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003038 return GetNameFromUnqualifiedId(D.getName());
3039}
3040
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003041/// \brief Retrieves the declaration name from a parsed unqualified-id.
3042DeclarationNameInfo
3043Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3044 DeclarationNameInfo NameInfo;
3045 NameInfo.setLoc(Name.StartLocation);
3046
Douglas Gregor7861a802009-11-03 01:35:08 +00003047 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003048
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003049 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003050 case UnqualifiedId::IK_Identifier:
3051 NameInfo.setName(Name.Identifier);
3052 NameInfo.setLoc(Name.StartLocation);
3053 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003054
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003055 case UnqualifiedId::IK_OperatorFunctionId:
3056 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3057 Name.OperatorFunctionId.Operator));
3058 NameInfo.setLoc(Name.StartLocation);
3059 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3060 = Name.OperatorFunctionId.SymbolLocations[0];
3061 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3062 = Name.EndLocation.getRawEncoding();
3063 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003064
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003065 case UnqualifiedId::IK_LiteralOperatorId:
3066 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3067 Name.Identifier));
3068 NameInfo.setLoc(Name.StartLocation);
3069 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3070 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003071
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003072 case UnqualifiedId::IK_ConversionFunctionId: {
3073 TypeSourceInfo *TInfo;
3074 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3075 if (Ty.isNull())
3076 return DeclarationNameInfo();
3077 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3078 Context.getCanonicalType(Ty)));
3079 NameInfo.setLoc(Name.StartLocation);
3080 NameInfo.setNamedTypeInfo(TInfo);
3081 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003082 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003083
3084 case UnqualifiedId::IK_ConstructorName: {
3085 TypeSourceInfo *TInfo;
3086 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3087 if (Ty.isNull())
3088 return DeclarationNameInfo();
3089 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3090 Context.getCanonicalType(Ty)));
3091 NameInfo.setLoc(Name.StartLocation);
3092 NameInfo.setNamedTypeInfo(TInfo);
3093 return NameInfo;
3094 }
3095
3096 case UnqualifiedId::IK_ConstructorTemplateId: {
3097 // In well-formed code, we can only have a constructor
3098 // template-id that refers to the current context, so go there
3099 // to find the actual type being constructed.
3100 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3101 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3102 return DeclarationNameInfo();
3103
3104 // Determine the type of the class being constructed.
3105 QualType CurClassType = Context.getTypeDeclType(CurClass);
3106
3107 // FIXME: Check two things: that the template-id names the same type as
3108 // CurClassType, and that the template-id does not occur when the name
3109 // was qualified.
3110
3111 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3112 Context.getCanonicalType(CurClassType)));
3113 NameInfo.setLoc(Name.StartLocation);
3114 // FIXME: should we retrieve TypeSourceInfo?
3115 NameInfo.setNamedTypeInfo(0);
3116 return NameInfo;
3117 }
3118
3119 case UnqualifiedId::IK_DestructorName: {
3120 TypeSourceInfo *TInfo;
3121 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3122 if (Ty.isNull())
3123 return DeclarationNameInfo();
3124 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3125 Context.getCanonicalType(Ty)));
3126 NameInfo.setLoc(Name.StartLocation);
3127 NameInfo.setNamedTypeInfo(TInfo);
3128 return NameInfo;
3129 }
3130
3131 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003132 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003133 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3134 return Context.getNameForTemplate(TName, TNameLoc);
3135 }
3136
3137 } // switch (Name.getKind())
3138
David Blaikie83d382b2011-09-23 05:06:16 +00003139 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003140}
3141
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003142static QualType getCoreType(QualType Ty) {
3143 do {
3144 if (Ty->isPointerType() || Ty->isReferenceType())
3145 Ty = Ty->getPointeeType();
3146 else if (Ty->isArrayType())
3147 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3148 else
3149 return Ty.withoutLocalFastQualifiers();
3150 } while (true);
3151}
3152
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003153/// hasSimilarParameters - Determine whether the C++ functions Declaration
3154/// and Definition have "nearly" matching parameters. This heuristic is
3155/// used to improve diagnostics in the case where an out-of-line function
3156/// definition doesn't match any declaration within the class or namespace.
3157/// Also sets Params to the list of indices to the parameters that differ
3158/// between the declaration and the definition. If hasSimilarParameters
3159/// returns true and Params is empty, then all of the parameters match.
3160static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003161 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003162 FunctionDecl *Definition,
3163 llvm::SmallVectorImpl<unsigned> &Params) {
3164 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003165 if (Declaration->param_size() != Definition->param_size())
3166 return false;
3167 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3168 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3169 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3170
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003171 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003172 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003173 continue;
3174
3175 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3176 QualType DefParamBaseTy = getCoreType(DefParamTy);
3177 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3178 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3179
3180 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3181 (DeclTyName && DeclTyName == DefTyName))
3182 Params.push_back(Idx);
3183 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00003184 return false;
3185 }
3186
3187 return true;
3188}
3189
John McCall99b2fe52010-04-29 23:50:39 +00003190/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3191/// declarator needs to be rebuilt in the current instantiation.
3192/// Any bits of declarator which appear before the name are valid for
3193/// consideration here. That's specifically the type in the decl spec
3194/// and the base type in any member-pointer chunks.
3195static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3196 DeclarationName Name) {
3197 // The types we specifically need to rebuild are:
3198 // - typenames, typeofs, and decltypes
3199 // - types which will become injected class names
3200 // Of course, we also need to rebuild any type referencing such a
3201 // type. It's safest to just say "dependent", but we call out a
3202 // few cases here.
3203
3204 DeclSpec &DS = D.getMutableDeclSpec();
3205 switch (DS.getTypeSpecType()) {
3206 case DeclSpec::TST_typename:
3207 case DeclSpec::TST_typeofType:
Alexis Hunt4a257072011-05-19 05:37:45 +00003208 case DeclSpec::TST_decltype:
Eli Friedman0dfb8892011-10-06 23:00:33 +00003209 case DeclSpec::TST_underlyingType:
3210 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00003211 // Grab the type from the parser.
3212 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00003213 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00003214 if (T.isNull() || !T->isDependentType()) break;
3215
3216 // Make sure there's a type source info. This isn't really much
3217 // of a waste; most dependent types should have type source info
3218 // attached already.
3219 if (!TSI)
3220 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3221
3222 // Rebuild the type in the current instantiation.
3223 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3224 if (!TSI) return true;
3225
3226 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00003227 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3228 DS.UpdateTypeRep(LocType);
3229 break;
3230 }
3231
3232 case DeclSpec::TST_typeofExpr: {
3233 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00003234 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00003235 if (Result.isInvalid()) return true;
3236 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00003237 break;
3238 }
3239
3240 default:
3241 // Nothing to do for these decl specs.
3242 break;
3243 }
3244
3245 // It doesn't matter what order we do this in.
3246 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3247 DeclaratorChunk &Chunk = D.getTypeObject(I);
3248
3249 // The only type information in the declarator which can come
3250 // before the declaration name is the base type of a member
3251 // pointer.
3252 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3253 continue;
3254
3255 // Rebuild the scope specifier in-place.
3256 CXXScopeSpec &SS = Chunk.Mem.Scope();
3257 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3258 return true;
3259 }
3260
3261 return false;
3262}
3263
Anders Carlsson1052fd72011-07-04 16:28:17 +00003264Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00003265 D.setFunctionDefinitionKind(FDK_Declaration);
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003266 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3267
3268 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00003269 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003270 Dcl->setTopLevelDeclInObjCContainer();
3271
3272 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00003273}
3274
Richard Smithdda56e42011-04-15 14:24:37 +00003275/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3276/// If T is the name of a class, then each of the following shall have a
3277/// name different from T:
3278/// - every static data member of class T;
3279/// - every member function of class T
3280/// - every member of class T that is itself a type;
3281/// \returns true if the declaration name violates these rules.
3282bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3283 DeclarationNameInfo NameInfo) {
3284 DeclarationName Name = NameInfo.getName();
3285
3286 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3287 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3288 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3289 return true;
3290 }
3291
3292 return false;
3293}
Douglas Gregor31feb332012-03-17 23:06:31 +00003294
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003295/// \brief Diagnose a declaration whose declarator-id has the given
3296/// nested-name-specifier.
3297///
3298/// \param SS The nested-name-specifier of the declarator-id.
3299///
3300/// \param DC The declaration context to which the nested-name-specifier
3301/// resolves.
3302///
3303/// \param Name The name of the entity being declared.
3304///
3305/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00003306///
3307/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003308bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00003309 DeclarationName Name,
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003310 SourceLocation Loc) {
3311 DeclContext *Cur = CurContext;
3312 while (isa<LinkageSpecDecl>(Cur))
3313 Cur = Cur->getParent();
3314
3315 // C++ [dcl.meaning]p1:
3316 // A declarator-id shall not be qualified except for the definition
3317 // of a member function (9.3) or static data member (9.4) outside of
3318 // its class, the definition or explicit instantiation of a function
3319 // or variable member of a namespace outside of its namespace, or the
3320 // definition of an explicit specialization outside of its namespace,
3321 // or the declaration of a friend function that is a member of
3322 // another class or namespace (11.3). [...]
3323
3324 // The user provided a superfluous scope specifier that refers back to the
3325 // class or namespaces in which the entity is already declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00003326 //
3327 // class X {
3328 // void X::f();
3329 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003330 if (Cur->Equals(DC)) {
Douglas Gregor31feb332012-03-17 23:06:31 +00003331 Diag(Loc, diag::warn_member_extra_qualification)
3332 << Name << FixItHint::CreateRemoval(SS.getRange());
3333 SS.clear();
3334 return false;
3335 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003336
3337 // Check whether the qualifying scope encloses the scope of the original
3338 // declaration.
3339 if (!Cur->Encloses(DC)) {
3340 if (Cur->isRecord())
3341 Diag(Loc, diag::err_member_qualification)
3342 << Name << SS.getRange();
3343 else if (isa<TranslationUnitDecl>(DC))
3344 Diag(Loc, diag::err_invalid_declarator_global_scope)
3345 << Name << SS.getRange();
3346 else if (isa<FunctionDecl>(Cur))
3347 Diag(Loc, diag::err_invalid_declarator_in_function)
3348 << Name << SS.getRange();
3349 else
3350 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00003351 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003352
Douglas Gregor31feb332012-03-17 23:06:31 +00003353 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003354 }
3355
3356 if (Cur->isRecord()) {
3357 // Cannot qualify members within a class.
3358 Diag(Loc, diag::err_member_qualification)
3359 << Name << SS.getRange();
3360 SS.clear();
3361
3362 // C++ constructors and destructors with incorrect scopes can break
3363 // our AST invariants by having the wrong underlying types. If
3364 // that's the case, then drop this declaration entirely.
3365 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3366 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3367 !Context.hasSameType(Name.getCXXNameType(),
3368 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3369 return true;
3370
3371 return false;
3372 }
Douglas Gregor31feb332012-03-17 23:06:31 +00003373
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003374 // C++11 [dcl.meaning]p1:
3375 // [...] "The nested-name-specifier of the qualified declarator-id shall
3376 // not begin with a decltype-specifer"
3377 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3378 while (SpecLoc.getPrefix())
3379 SpecLoc = SpecLoc.getPrefix();
3380 if (dyn_cast_or_null<DecltypeType>(
3381 SpecLoc.getNestedNameSpecifier()->getAsType()))
3382 Diag(Loc, diag::err_decltype_in_declarator)
3383 << SpecLoc.getTypeLoc().getSourceRange();
3384
Douglas Gregor31feb332012-03-17 23:06:31 +00003385 return false;
3386}
3387
John McCall48871652010-08-21 09:40:31 +00003388Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003389 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003390 // TODO: consider using NameInfo for diagnostic.
3391 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3392 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00003393
Chris Lattner02c04392007-07-25 00:24:17 +00003394 // All of these full declarators require an identifier. If it doesn't have
3395 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00003396 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003397 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003398 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003399 diag::err_declarator_need_ident)
3400 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00003401 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00003402 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3403 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003404
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003405 // The scope passed in may not be a decl scope. Zip up the scope tree until
3406 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00003407 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003408 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003409 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003410
John McCall99b2fe52010-04-29 23:50:39 +00003411 DeclContext *DC = CurContext;
3412 if (D.getCXXScopeSpec().isInvalid())
3413 D.setInvalidType();
3414 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003415 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3416 UPPC_DeclarationQualifier))
3417 return 0;
3418
John McCall99b2fe52010-04-29 23:50:39 +00003419 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3420 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3421 if (!DC) {
3422 // If we could not compute the declaration context, it's because the
3423 // declaration context is dependent but does not refer to a class,
3424 // class template, or class template partial specialization. Complain
3425 // and return early, to avoid the coming semantic disaster.
3426 Diag(D.getIdentifierLoc(),
3427 diag::err_template_qualified_declarator_no_match)
3428 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3429 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003430 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003431 }
John McCall99b2fe52010-04-29 23:50:39 +00003432 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003433
John McCall99b2fe52010-04-29 23:50:39 +00003434 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003435 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003436 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003437
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003438 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3439 Diag(D.getIdentifierLoc(),
3440 diag::err_member_def_undefined_record)
3441 << Name << DC << D.getCXXScopeSpec().getRange();
3442 D.setInvalidType();
3443 } else if (!D.getDeclSpec().isFriendSpecified()) {
3444 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3445 Name, D.getIdentifierLoc())) {
3446 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00003447 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003448
3449 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00003450 }
John McCall99b2fe52010-04-29 23:50:39 +00003451 }
3452
3453 // Check whether we need to rebuild the type of the given
3454 // declaration in the current instantiation.
3455 if (EnteringContext && IsDependentContext &&
3456 TemplateParamLists.size() != 0) {
3457 ContextRAII SavedContext(*this, DC);
3458 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3459 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003460 }
3461 }
Richard Smithdda56e42011-04-15 14:24:37 +00003462
3463 if (DiagnoseClassNameShadow(DC, NameInfo))
3464 // If this is a typedef, we'll end up spewing multiple diagnostics.
3465 // Just return early; it's safer.
3466 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3467 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003468
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003469 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003470
John McCall8cb7bdf2010-06-04 23:28:52 +00003471 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3472 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003473
Douglas Gregor506bd562010-12-13 22:49:22 +00003474 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3475 UPPC_DeclarationType))
3476 D.setInvalidType();
3477
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003478 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003479 ForRedeclaration);
3480
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003481 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003482 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003483 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003484
3485 // If the declaration we're planning to build will be a function
3486 // or object with linkage, then look for another declaration with
3487 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3488 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3489 /* Do nothing*/;
3490 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003491 if (CurContext->isFunctionOrMethod() ||
3492 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003493 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003494 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003495 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003496 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003497 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003498 IsLinkageLookup = true;
3499
3500 if (IsLinkageLookup)
3501 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003502
John McCall1f82f242009-11-18 22:49:29 +00003503 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003504 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003505 LookupQualifiedName(Previous, DC);
3506
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003507 // C++ [dcl.meaning]p1:
3508 // When the declarator-id is qualified, the declaration shall refer to a
3509 // previously declared member of the class or namespace to which the
3510 // qualifier refers (or, in the case of a namespace, of an element of the
3511 // inline namespace set of that namespace (7.3.1)) or to a specialization
3512 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003513 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003514 // Note that we already checked the context above, and that we do not have
3515 // enough information to make sure that Previous contains the declaration
3516 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00003517 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003518 // class X {
3519 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003520 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003521 // };
3522 //
Douglas Gregorad590502008-12-15 23:53:10 +00003523 // void X::f(int) { } // ill-formed
3524 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003525 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00003526 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003527 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003528
3529 // C++ [dcl.meaning]p1:
3530 // [...] the member shall not merely have been introduced by a
3531 // using-declaration in the scope of the class or namespace nominated by
3532 // the nested-name-specifier of the declarator-id.
3533 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003534 }
3535
John McCall1f82f242009-11-18 22:49:29 +00003536 if (Previous.isSingleResult() &&
3537 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003538 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003539 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00003540 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3541 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003542
Douglas Gregor5101c242008-12-05 18:15:24 +00003543 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003544 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003545 }
3546
Douglas Gregor83a586e2008-04-13 21:07:44 +00003547 // In C++, the previous declaration we find might be a tag type
3548 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003549 // tag type. Note that this does does not apply if we're declaring a
3550 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003551 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003552 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003553 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003554
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003555 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00003556 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003557 if (TemplateParamLists.size()) {
3558 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003559 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003560 }
Mike Stump11289f42009-09-09 15:08:12 +00003561
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003562 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003563 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003564 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003565 move(TemplateParamLists),
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003566 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00003567 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003568 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3569 move(TemplateParamLists));
Chris Lattner01a7c532007-01-25 23:09:03 +00003570 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003571
3572 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003573 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003574
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003575 // If this has an identifier and is not an invalid redeclaration or
3576 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003577 if (New->getDeclName() && AddToScope &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003578 !(D.isRedeclaration() && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003579 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003580
John McCall48871652010-08-21 09:40:31 +00003581 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003582}
3583
Eli Friedmana3b1d032009-02-21 00:44:51 +00003584/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3585/// types into constant array types in certain situations which would otherwise
3586/// be errors (for GCC compatibility).
3587static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3588 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003589 bool &SizeIsNegative,
3590 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003591 // This method tries to turn a variable array into a constant
3592 // array even when the size isn't an ICE. This is necessary
3593 // for compatibility with code that depends on gcc's buggy
3594 // constant expression folding, like struct {char x[(int)(char*)2];}
3595 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003596 Oversized = 0;
3597
3598 if (T->isDependentType())
3599 return QualType();
3600
John McCall8ccfcb52009-09-24 19:53:00 +00003601 QualifierCollector Qs;
3602 const Type *Ty = Qs.strip(T);
3603
3604 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003605 QualType Pointee = PTy->getPointeeType();
3606 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003607 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3608 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003609 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003610 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003611 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003612 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003613 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3614 QualType Inner = PTy->getInnerType();
3615 QualType FixedType =
3616 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3617 Oversized);
3618 if (FixedType.isNull()) return FixedType;
3619 FixedType = Context.getParenType(FixedType);
3620 return Qs.apply(Context, FixedType);
3621 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003622
3623 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003624 if (!VLATy)
3625 return QualType();
3626 // FIXME: We should probably handle this case
3627 if (VLATy->getElementType()->isVariablyModifiedType())
3628 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003629
Richard Smith42d3af92011-12-07 00:43:50 +00003630 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003631 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00003632 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00003633 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003634
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003635 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003636 if (Res.isSigned() && Res.isNegative()) {
3637 SizeIsNegative = true;
3638 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003639 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003640
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003641 // Check whether the array is too large to be addressed.
3642 unsigned ActiveSizeBits
3643 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3644 Res);
3645 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3646 Oversized = Res;
3647 return QualType();
3648 }
3649
3650 return Context.getConstantArrayType(VLATy->getElementType(),
3651 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003652}
3653
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003654/// \brief Register the given locally-scoped external C declaration so
3655/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003656void
John McCall1f82f242009-11-18 22:49:29 +00003657Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3658 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003659 Scope *S) {
3660 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3661 "Decl is not a locally-scoped decl!");
3662 // Note that we have a locally-scoped external with this name.
3663 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3664
John McCall1f82f242009-11-18 22:49:29 +00003665 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003666 return;
3667
John McCall1f82f242009-11-18 22:49:29 +00003668 NamedDecl *PrevDecl = Previous.getFoundDecl();
3669
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003670 // If there was a previous declaration of this variable, it may be
3671 // in our identifier chain. Update the identifier chain with the new
3672 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003673 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003674 // The previous declaration was found on the identifer resolver
3675 // chain, so remove it from its scope.
Douglas Gregor825faf72011-06-29 21:22:02 +00003676
3677 if (S->isDeclScope(PrevDecl)) {
3678 // Special case for redeclarations in the SAME scope.
3679 // Because this declaration is going to be added to the identifier chain
3680 // later, we should temporarily take it OFF the chain.
3681 IdResolver.RemoveDecl(ND);
3682
3683 } else {
3684 // Find the scope for the original declaration.
3685 while (S && !S->isDeclScope(PrevDecl))
3686 S = S->getParent();
3687 }
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003688
3689 if (S)
John McCall48871652010-08-21 09:40:31 +00003690 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003691 }
3692}
3693
Douglas Gregordc5c9582011-07-28 14:20:37 +00003694llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3695Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3696 if (ExternalSource) {
3697 // Load locally-scoped external decls from the external source.
3698 SmallVector<NamedDecl *, 4> Decls;
3699 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3700 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3701 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3702 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3703 if (Pos == LocallyScopedExternalDecls.end())
3704 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3705 }
3706 }
3707
3708 return LocallyScopedExternalDecls.find(Name);
3709}
3710
Eli Friedman574c7452009-04-07 19:37:57 +00003711/// \brief Diagnose function specifiers on a declaration of an identifier that
3712/// does not identify a function.
3713void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3714 // FIXME: We should probably indicate the identifier in question to avoid
3715 // confusion for constructs like "inline int a(), b;"
3716 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003717 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003718 diag::err_inline_non_function);
3719
3720 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003721 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003722 diag::err_virtual_non_function);
3723
3724 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003725 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003726 diag::err_explicit_non_function);
3727}
3728
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003729NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003730Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003731 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003732 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3733 if (D.getCXXScopeSpec().isSet()) {
3734 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3735 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003736 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003737 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00003738 DC = CurContext;
3739 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003740 }
3741
David Blaikiebbafb8a2012-03-11 07:00:24 +00003742 if (getLangOpts().CPlusPlus) {
Douglas Gregor0c880302009-03-11 23:00:04 +00003743 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003744 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003745 }
3746
Eli Friedman574c7452009-04-07 19:37:57 +00003747 DiagnoseFunctionSpecifiers(D);
3748
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003749 if (D.getDeclSpec().isThreadSpecified())
3750 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00003751 if (D.getDeclSpec().isConstexprSpecified())
3752 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3753 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003754
Douglas Gregord8f446f2010-07-13 06:37:01 +00003755 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3756 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3757 << D.getName().getSourceRange();
3758 return 0;
3759 }
3760
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003761 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003762 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003763
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003764 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003765 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00003766
Richard Smith3f1b5d02011-05-05 21:57:07 +00003767 CheckTypedefForVariablyModifiedType(S, NewTD);
3768
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003769 bool Redeclaration = D.isRedeclaration();
3770 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3771 D.setRedeclaration(Redeclaration);
3772 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00003773}
3774
Richard Smith3f1b5d02011-05-05 21:57:07 +00003775void
3776Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00003777 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3778 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00003779 // Note that variably modified types must be fixed before merging the decl so
3780 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00003781 QualType T = NewTD->getUnderlyingType();
3782 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00003783 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003784
Chris Lattner9fecd742009-04-19 05:21:20 +00003785 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003786 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003787 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003788 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003789 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3790 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003791 if (!FixedTy.isNull()) {
Richard Smithdda56e42011-04-15 14:24:37 +00003792 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00003793 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00003794 } else {
3795 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00003796 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003797 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00003798 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003799 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00003800 Diag(NewTD->getLocation(), diag::err_array_too_large)
3801 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003802 else
Richard Smithdda56e42011-04-15 14:24:37 +00003803 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003804 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00003805 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003806 }
3807 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003808}
Douglas Gregor27821ce2009-07-07 16:35:42 +00003809
Richard Smith3f1b5d02011-05-05 21:57:07 +00003810
3811/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3812/// declares a typedef-name, either using the 'typedef' type specifier or via
3813/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3814NamedDecl*
3815Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3816 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00003817 // Merge the decl with the existing one if appropriate. If the decl is
3818 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003819 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00003820 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003821 if (!Previous.empty()) {
3822 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00003823 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003824 }
3825
Douglas Gregor27821ce2009-07-07 16:35:42 +00003826 // If this is the C FILE type, notify the AST context.
3827 if (IdentifierInfo *II = NewTD->getIdentifier())
3828 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003829 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00003830 if (II->isStr("FILE"))
3831 Context.setFILEDecl(NewTD);
3832 else if (II->isStr("jmp_buf"))
3833 Context.setjmp_bufDecl(NewTD);
3834 else if (II->isStr("sigjmp_buf"))
3835 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00003836 else if (II->isStr("ucontext_t"))
3837 Context.setucontext_tDecl(NewTD);
Douglas Gregor2c2c4cd2010-10-05 15:41:24 +00003838 else if (II->isStr("__builtin_va_list"))
3839 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stumpa4de80b2009-07-28 02:25:19 +00003840 }
3841
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003842 return NewTD;
3843}
3844
Douglas Gregor5d68a202009-02-24 19:23:27 +00003845/// \brief Determines whether the given declaration is an out-of-scope
3846/// previous declaration.
3847///
3848/// This routine should be invoked when name lookup has found a
3849/// previous declaration (PrevDecl) that is not in the scope where a
3850/// new declaration by the same name is being introduced. If the new
3851/// declaration occurs in a local scope, previous declarations with
3852/// linkage may still be considered previous declarations (C99
3853/// 6.2.2p4-5, C++ [basic.link]p6).
3854///
3855/// \param PrevDecl the previous declaration found by name
3856/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00003857///
Douglas Gregor5d68a202009-02-24 19:23:27 +00003858/// \param DC the context in which the new declaration is being
3859/// declared.
3860///
3861/// \returns true if PrevDecl is an out-of-scope previous declaration
3862/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00003863static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00003864isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3865 ASTContext &Context) {
3866 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00003867 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003868
Douglas Gregoreddf4332009-02-24 20:03:32 +00003869 if (!PrevDecl->hasLinkage())
3870 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003871
David Blaikiebbafb8a2012-03-11 07:00:24 +00003872 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00003873 // C++ [basic.link]p6:
3874 // If there is a visible declaration of an entity with linkage
3875 // having the same name and type, ignoring entities declared
3876 // outside the innermost enclosing namespace scope, the block
3877 // scope declaration declares that same entity and receives the
3878 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00003879 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00003880 if (!OuterContext->isFunctionOrMethod())
3881 // This rule only applies to block-scope declarations.
3882 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00003883
3884 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3885 if (PrevOuterContext->isRecord())
3886 // We found a member function: ignore it.
3887 return false;
3888
3889 // Find the innermost enclosing namespace for the new and
3890 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00003891 OuterContext = OuterContext->getEnclosingNamespaceContext();
3892 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00003893
Douglas Gregorfcee9462010-08-27 22:55:10 +00003894 // The previous declaration is in a different namespace, so it
3895 // isn't the same function.
3896 if (!OuterContext->Equals(PrevOuterContext))
3897 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003898 }
3899
Douglas Gregor5d68a202009-02-24 19:23:27 +00003900 return true;
3901}
3902
John McCall3e11ebe2010-03-15 10:12:16 +00003903static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3904 CXXScopeSpec &SS = D.getCXXScopeSpec();
3905 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00003906 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00003907}
3908
John McCall31168b02011-06-15 23:02:42 +00003909bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3910 QualType type = decl->getType();
3911 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3912 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3913 // Various kinds of declaration aren't allowed to be __autoreleasing.
3914 unsigned kind = -1U;
3915 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3916 if (var->hasAttr<BlocksAttr>())
3917 kind = 0; // __block
3918 else if (!var->hasLocalStorage())
3919 kind = 1; // global
3920 } else if (isa<ObjCIvarDecl>(decl)) {
3921 kind = 3; // ivar
3922 } else if (isa<FieldDecl>(decl)) {
3923 kind = 2; // field
3924 }
3925
3926 if (kind != -1U) {
3927 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3928 << kind;
3929 }
3930 } else if (lifetime == Qualifiers::OCL_None) {
3931 // Try to infer lifetime.
3932 if (!type->isObjCLifetimeType())
3933 return false;
3934
3935 lifetime = type->getObjCARCImplicitLifetime();
3936 type = Context.getLifetimeQualifiedType(type, lifetime);
3937 decl->setType(type);
3938 }
3939
3940 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3941 // Thread-local variables cannot have lifetime.
3942 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3943 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003944 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00003945 << var->getType();
3946 return true;
3947 }
3948 }
3949
3950 return false;
3951}
3952
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003953NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00003954Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003955 TypeSourceInfo *TInfo, LookupResult &Previous,
3956 MultiTemplateParamsArg TemplateParamLists) {
3957 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003958 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003959
3960 // Check that there are no default arguments (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00003961 if (getLangOpts().CPlusPlus)
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003962 CheckExtraCXXDefaultArguments(D);
3963
Douglas Gregorc4df4072010-04-19 22:54:31 +00003964 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3965 assert(SCSpec != DeclSpec::SCS_typedef &&
3966 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003967 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003968 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003969 // mutable can only appear on non-static class members, so it's always
3970 // an error here
3971 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003972 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003973 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003974 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003975 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3976 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003977 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003978
3979 IdentifierInfo *II = Name.getAsIdentifierInfo();
3980 if (!II) {
3981 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00003982 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003983 return 0;
3984 }
3985
Eli Friedman574c7452009-04-07 19:37:57 +00003986 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003987
Douglas Gregor212cab32009-03-11 20:22:50 +00003988 if (!DC->isRecord() && S->getFnParent() == 0) {
3989 // C99 6.9p2: The storage-class specifiers auto and register shall not
3990 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00003991 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00003992
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003993 // If this is a register variable with an asm label specified, then this
3994 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00003995 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003996 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3997 else
3998 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003999 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004000 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004001 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004002
David Blaikiebbafb8a2012-03-11 07:00:24 +00004003 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004004 // Set up the special work-group-local storage class for variables in the
4005 // OpenCL __local address space.
4006 if (R.getAddressSpace() == LangAS::opencl_local)
4007 SC = SC_OpenCLWorkGroupLocal;
4008 }
4009
Ted Kremenek582a0992011-01-23 17:04:59 +00004010 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004011 VarDecl *NewVD;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004012 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004013 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004014 D.getIdentifierLoc(), II,
4015 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004016
4017 if (D.isInvalidType())
4018 NewVD->setInvalidDecl();
4019 } else {
4020 if (DC->isRecord() && !CurContext->isRecord()) {
4021 // This is an out-of-line definition of a static data member.
4022 if (SC == SC_Static) {
4023 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4024 diag::err_static_out_of_line)
4025 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4026 } else if (SC == SC_None)
4027 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00004028 }
Richard Smith42973752012-02-16 20:41:22 +00004029 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004030 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4031 if (RD->isLocalClass())
4032 Diag(D.getIdentifierLoc(),
4033 diag::err_static_data_member_not_allowed_in_local_class)
4034 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004035
Richard Smith42973752012-02-16 20:41:22 +00004036 // C++98 [class.union]p1: If a union contains a static data member,
4037 // the program is ill-formed. C++11 drops this restriction.
4038 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004039 Diag(D.getIdentifierLoc(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00004040 getLangOpts().CPlusPlus0x
Richard Smith42973752012-02-16 20:41:22 +00004041 ? diag::warn_cxx98_compat_static_data_member_in_union
4042 : diag::ext_static_data_member_in_union) << Name;
4043 // We conservatively disallow static data members in anonymous structs.
4044 else if (!RD->getDeclName())
4045 Diag(D.getIdentifierLoc(),
4046 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004047 << Name << RD->isUnion();
4048 }
4049 }
4050
4051 // Match up the template parameter lists with the scope specifier, then
4052 // determine whether we have a template or a template specialization.
4053 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004054 bool Invalid = false;
4055 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004056 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004057 D.getDeclSpec().getLocStart(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004058 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004059 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00004060 TemplateParamLists.get(),
4061 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00004062 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004063 isExplicitSpecialization,
4064 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004065 if (TemplateParams->size() > 0) {
4066 // There is no such thing as a variable template.
4067 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4068 << II
4069 << SourceRange(TemplateParams->getTemplateLoc(),
4070 TemplateParams->getRAngleLoc());
4071 return 0;
4072 } else {
4073 // There is an extraneous 'template<>' for this variable. Complain
4074 // about it, but allow the declaration of the variable.
4075 Diag(TemplateParams->getTemplateLoc(),
4076 diag::err_template_variable_noparams)
4077 << II
4078 << SourceRange(TemplateParams->getTemplateLoc(),
4079 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004080 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00004081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004083 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004084 D.getIdentifierLoc(), II,
4085 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004086
Richard Smithb2bc2e62011-02-21 20:05:19 +00004087 // If this decl has an auto type in need of deduction, make a note of the
4088 // Decl so we can diagnose uses of it in its own initializer.
4089 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4090 R->getContainedAutoType())
4091 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00004092
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004093 if (D.isInvalidType() || Invalid)
4094 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004095
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004096 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00004097
Abramo Bagnara60804e12011-03-18 15:16:37 +00004098 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004099 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00004100 TemplateParamLists.size(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004101 TemplateParamLists.release());
4102 }
Richard Smitha77a0a62011-08-15 21:04:07 +00004103
Richard Smith6331c402012-02-13 22:16:19 +00004104 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00004105 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004106 }
4107
Douglas Gregor41866812011-09-12 18:37:38 +00004108 // Set the lexical context. If the declarator has a C++ scope specifier, the
4109 // lexical context will be different from the semantic context.
4110 NewVD->setLexicalDeclContext(CurContext);
4111
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004112 if (D.getDeclSpec().isThreadSpecified()) {
4113 if (NewVD->hasLocalStorage())
4114 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Douglas Gregore8bbc122011-09-02 00:18:52 +00004115 else if (!Context.getTargetInfo().isTLSSupported())
Eli Friedmandaea3f62009-04-19 21:48:33 +00004116 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004117 else
4118 NewVD->setThreadSpecified(true);
4119 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004120
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00004121 if (D.getDeclSpec().isModulePrivateSpecified()) {
4122 if (isExplicitSpecialization)
4123 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4124 << 2
4125 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00004126 else if (NewVD->hasLocalStorage())
4127 Diag(NewVD->getLocation(), diag::err_module_private_local)
4128 << 0 << NewVD->getDeclName()
4129 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4130 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00004131 else
4132 NewVD->setModulePrivate();
4133 }
Douglas Gregor26701a42011-09-09 02:06:17 +00004134
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004135 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004136 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004137
John McCall31168b02011-06-15 23:02:42 +00004138 // In auto-retain/release, infer strong retension for variables of
4139 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004140 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00004141 NewVD->setInvalidDecl();
4142
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004143 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00004144 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004145 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004146 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004147 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00004148 if (S->getFnParent() != 0) {
4149 switch (SC) {
4150 case SC_None:
4151 case SC_Auto:
4152 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4153 break;
4154 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00004155 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00004156 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4157 break;
4158 case SC_Static:
4159 case SC_Extern:
4160 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004161 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00004162 break;
4163 }
4164 }
4165
4166 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00004167 Context, Label));
David Chisnall0867d9c2012-02-18 16:12:34 +00004168 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4169 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4170 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4171 if (I != ExtnameUndeclaredIdentifiers.end()) {
4172 NewVD->addAttr(I->second);
4173 ExtnameUndeclaredIdentifiers.erase(I);
4174 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004175 }
4176
John McCalla2a3f7d2010-03-16 21:48:18 +00004177 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00004178 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00004179 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00004180
John McCall1f82f242009-11-18 22:49:29 +00004181 // Don't consider existing declarations that are in a different
4182 // scope and are out-of-semantic-context declarations (if the new
4183 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00004184 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004185 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004186
David Blaikiebbafb8a2012-03-11 07:00:24 +00004187 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004188 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4189 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004190 // Merge the decl with the existing one if appropriate.
4191 if (!Previous.empty()) {
4192 if (Previous.isSingleResult() &&
4193 isa<FieldDecl>(Previous.getFoundDecl()) &&
4194 D.getCXXScopeSpec().isSet()) {
4195 // The user tried to define a non-static data member
4196 // out-of-line (C++ [dcl.meaning]p1).
4197 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4198 << D.getCXXScopeSpec().getRange();
4199 Previous.clear();
4200 NewVD->setInvalidDecl();
4201 }
4202 } else if (D.getCXXScopeSpec().isSet()) {
4203 // No previous declaration in the qualifying scope.
4204 Diag(D.getIdentifierLoc(), diag::err_no_member)
4205 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004206 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004207 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004208 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004209
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004210 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004211
4212 // This is an explicit specialization of a static data member. Check it.
4213 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4214 CheckMemberSpecialization(NewVD, Previous))
4215 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004216 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004217
Ryan Flynne5dc8592009-07-25 22:29:44 +00004218 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004219 // FIXME: This should be handled in attribute merging, not
4220 // here.
John McCall1f82f242009-11-18 22:49:29 +00004221 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00004222 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4223 if (Def && (Def = Def->getDefinition()) &&
4224 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00004225 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4226 Diag(Def->getLocation(), diag::note_previous_definition);
4227 }
4228 }
4229
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004230 // If this is a locally-scoped extern C variable, update the map of
4231 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00004232 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004233 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004234 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004235
Eli Friedman570024a2010-08-05 06:57:20 +00004236 // If there's a #pragma GCC visibility in scope, and this isn't a class
4237 // member, set the visibility of this variable.
4238 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4239 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004240
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004241 MarkUnusedFileScopedDecl(NewVD);
4242
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004243 return NewVD;
4244}
4245
John McCalldf8b37c2010-03-22 09:20:08 +00004246/// \brief Diagnose variable or built-in function shadowing. Implements
4247/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00004248///
John McCalldf8b37c2010-03-22 09:20:08 +00004249/// This method is called whenever a VarDecl is added to a "useful"
4250/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00004251///
John McCall2d8c7602010-03-20 04:12:52 +00004252/// \param S the scope in which the shadowing name is being declared
4253/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00004254///
John McCalldf8b37c2010-03-22 09:20:08 +00004255void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00004256 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004257 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00004258 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00004259 return;
4260
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00004261 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00004262 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00004263 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00004264
4265 DeclContext *NewDC = D->getDeclContext();
4266
John McCall2d8c7602010-03-20 04:12:52 +00004267 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00004268 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00004269 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00004270
John McCalla2a3f7d2010-03-16 21:48:18 +00004271 NamedDecl* ShadowedDecl = R.getFoundDecl();
4272 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4273 return;
4274
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00004275 // Fields are not shadowed by variables in C++ static methods.
4276 if (isa<FieldDecl>(ShadowedDecl))
4277 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4278 if (MD->isStatic())
4279 return;
4280
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00004281 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4282 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00004283 // For shadowing external vars, make sure that we point to the global
4284 // declaration, not a locally scoped extern declaration.
4285 for (VarDecl::redecl_iterator
4286 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4287 I != E; ++I)
4288 if (I->isFileVarDecl()) {
4289 ShadowedDecl = *I;
4290 break;
4291 }
4292 }
4293
4294 DeclContext *OldDC = ShadowedDecl->getDeclContext();
4295
John McCall2d8c7602010-03-20 04:12:52 +00004296 // Only warn about certain kinds of shadowing for class members.
4297 if (NewDC && NewDC->isRecord()) {
4298 // In particular, don't warn about shadowing non-class members.
4299 if (!OldDC->isRecord())
4300 return;
4301
4302 // TODO: should we warn about static data members shadowing
4303 // static data members from base classes?
4304
4305 // TODO: don't diagnose for inaccessible shadowed members.
4306 // This is hard to do perfectly because we might friend the
4307 // shadowing context, but that's just a false negative.
4308 }
4309
4310 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00004311 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00004312 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00004313 if (isa<FieldDecl>(ShadowedDecl))
4314 Kind = 3; // field
4315 else
4316 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00004317 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00004318 Kind = 1; // global
4319 else
4320 Kind = 0; // local
4321
John McCall2d8c7602010-03-20 04:12:52 +00004322 DeclarationName Name = R.getLookupName();
4323
John McCalla2a3f7d2010-03-16 21:48:18 +00004324 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00004325 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00004326 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4327}
4328
John McCalldf8b37c2010-03-22 09:20:08 +00004329/// \brief Check -Wshadow without the advantage of a previous lookup.
4330void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004331 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00004332 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004333 return;
4334
John McCalldf8b37c2010-03-22 09:20:08 +00004335 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4336 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4337 LookupName(R, S);
4338 CheckShadow(S, D, R);
4339}
4340
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004341/// \brief Perform semantic checking on a newly-created variable
4342/// declaration.
4343///
4344/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004345/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004346/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004347/// have been translated into a declaration, and to check variables
4348/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004349///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004350/// Sets NewVD->isInvalidDecl() if an error was encountered.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004351///
4352/// Returns true if the variable declaration is a redeclaration.
4353bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4354 LookupResult &Previous) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004355 // If the decl is already known invalid, don't check it.
4356 if (NewVD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004357 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004358
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004359 QualType T = NewVD->getType();
4360
John McCall8b07ec22010-05-15 11:32:37 +00004361 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00004362 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4363 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004364 T = Context.getObjCObjectPointerType(T);
4365 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004366 }
Mike Stump11289f42009-09-09 15:08:12 +00004367
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004368 // Emit an error if an address space was applied to decl with local storage.
4369 // This includes arrays of objects with address space qualifiers, but not
4370 // automatic variables that point to other address spaces.
4371 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00004372 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004373 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004374 NewVD->setInvalidDecl();
4375 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004376 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00004377
Mike Stumpca5ae662009-04-14 00:57:29 +00004378 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004379 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004380 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004381 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4382 else
4383 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4384 }
Chris Lattner88fdea82010-10-10 18:16:20 +00004385
Chris Lattner9fecd742009-04-19 05:21:20 +00004386 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00004387 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00004388 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00004389 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004390
Chris Lattner9fecd742009-04-19 05:21:20 +00004391 if ((isVM && NewVD->hasLinkage()) ||
4392 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004393 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004394 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00004395 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004396 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4397 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00004398
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004399 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004400 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00004401 // FIXME: This won't give the correct result for
4402 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00004403 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004404
Anders Carlsson6c885802009-02-28 21:56:50 +00004405 if (NewVD->isFileVarDecl())
4406 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004407 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00004408 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00004409 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004410 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00004411 else
4412 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004413 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004414 NewVD->setInvalidDecl();
4415 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004416 }
4417
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004418 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004419 if (NewVD->isFileVarDecl())
4420 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4421 else
4422 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004423 NewVD->setInvalidDecl();
4424 return false;
Anders Carlsson6c885802009-02-28 21:56:50 +00004425 }
Mike Stump11289f42009-09-09 15:08:12 +00004426
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004427 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4428 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00004429 }
4430
John McCall1f82f242009-11-18 22:49:29 +00004431 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004432 // Since we did not find anything by this name and we're declaring
4433 // an extern "C" variable, look for a non-visible extern "C"
4434 // declaration with the same name.
4435 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00004436 = findLocallyScopedExternalDecl(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004437 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004438 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004439 }
4440
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004441 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004442 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4443 << T;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004444 NewVD->setInvalidDecl();
4445 return false;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004446 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004447
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004448 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004449 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004450 NewVD->setInvalidDecl();
4451 return false;
Mike Stumpe9efa802009-04-30 00:19:40 +00004452 }
Mike Stump11289f42009-09-09 15:08:12 +00004453
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004454 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004455 Diag(NewVD->getLocation(), diag::err_block_on_vm);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004456 NewVD->setInvalidDecl();
4457 return false;
Mike Stumpa7128632009-05-01 23:41:47 +00004458 }
4459
Richard Smith6331c402012-02-13 22:16:19 +00004460 if (NewVD->isConstexpr() && !T->isDependentType() &&
4461 RequireLiteralType(NewVD->getLocation(), T,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00004462 diag::err_constexpr_var_non_literal)) {
Richard Smith6331c402012-02-13 22:16:19 +00004463 NewVD->setInvalidDecl();
4464 return false;
4465 }
4466
John McCall1f82f242009-11-18 22:49:29 +00004467 if (!Previous.empty()) {
John McCall1f82f242009-11-18 22:49:29 +00004468 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004469 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004470 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004471 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004472}
4473
Douglas Gregor36d1b142009-10-06 17:59:45 +00004474/// \brief Data used with FindOverriddenMethod
4475struct FindOverriddenMethodData {
4476 Sema *S;
4477 CXXMethodDecl *Method;
4478};
4479
4480/// \brief Member lookup function that determines whether a given C++
4481/// method overrides a method in a base class, to be used with
4482/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004483static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004484 CXXBasePath &Path,
4485 void *UserData) {
4486 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004487
Douglas Gregor36d1b142009-10-06 17:59:45 +00004488 FindOverriddenMethodData *Data
4489 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004490
4491 DeclarationName Name = Data->Method->getDeclName();
4492
4493 // FIXME: Do we care about other names here too?
4494 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004495 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004496 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4497 CanQualType CT = Data->S->Context.getCanonicalType(T);
4498
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004499 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004500 }
4501
4502 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004503 Path.Decls.first != Path.Decls.second;
4504 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004505 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004506 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4507 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004508 return true;
4509 }
4510 }
4511
4512 return false;
4513}
4514
Douglas Gregor433e0532012-04-16 18:27:27 +00004515static bool hasDelayedExceptionSpec(CXXMethodDecl *Method) {
4516 const FunctionProtoType *Proto =Method->getType()->getAs<FunctionProtoType>();
4517 return Proto && Proto->getExceptionSpecType() == EST_Delayed;
4518}
4519
Sebastian Redld5b24532009-11-18 21:51:29 +00004520/// AddOverriddenMethods - See if a method overrides any in the base classes,
4521/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004522bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004523 // Look for virtual methods in base classes that this method might override.
4524 CXXBasePaths Paths;
4525 FindOverriddenMethodData Data;
4526 Data.Method = MD;
4527 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004528 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004529 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4530 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4531 E = Paths.found_decls_end(); I != E; ++I) {
4532 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00004533 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00004534 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Douglas Gregor433e0532012-04-16 18:27:27 +00004535 (hasDelayedExceptionSpec(MD) ||
4536 !CheckOverridingFunctionExceptionSpec(MD, OldMD)) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004537 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004538 AddedAny = true;
4539 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004540 }
4541 }
4542 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004543
4544 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004545}
4546
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004547namespace {
4548 // Struct for holding all of the extra arguments needed by
4549 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4550 struct ActOnFDArgs {
4551 Scope *S;
4552 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004553 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004554 bool AddToScope;
4555 };
4556}
4557
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004558namespace {
4559
4560// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004561// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004562class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4563 public:
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004564 DifferentNameValidatorCCC(CXXRecordDecl *Parent)
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004565 : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004566
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004567 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004568 if (candidate.getEditDistance() == 0)
4569 return false;
4570
4571 if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) {
4572 CXXRecordDecl *Parent = MD->getParent();
4573 return Parent && Parent->getCanonicalDecl() == ExpectedParent;
4574 }
4575
4576 return !ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004577 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004578
4579 private:
4580 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004581};
4582
4583}
4584
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004585/// \brief Generate diagnostics for an invalid function redeclaration.
4586///
4587/// This routine handles generating the diagnostic messages for an invalid
4588/// function redeclaration, including finding possible similar declarations
4589/// or performing typo correction if there are no previous declarations with
4590/// the same name.
4591///
4592/// Returns a NamedDecl iff typo correction was performed and substituting in
4593/// the new declaration name does not cause new errors.
4594static NamedDecl* DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004595 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004596 ActOnFDArgs &ExtraArgs) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004597 NamedDecl *Result = NULL;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004598 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004599 DeclContext *NewDC = NewFD->getDeclContext();
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004600 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
John McCallf7cfb222010-10-13 05:45:15 +00004601 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004602 llvm::SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004603 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4604 TypoCorrection Correction;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004605 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004606 ExtraArgs.D.getDeclSpec().isFriendSpecified());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004607 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4608 : diag::err_member_def_does_not_match;
4609
4610 NewFD->setInvalidDecl();
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004611 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00004612 assert(!Prev.isAmbiguous() &&
4613 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004614 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4615 DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004616 if (!Prev.empty()) {
4617 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4618 Func != FuncEnd; ++Func) {
4619 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004620 if (FD &&
4621 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004622 // Add 1 to the index so that 0 can mean the mismatch didn't
4623 // involve a parameter
4624 unsigned ParamNum =
4625 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4626 NearMatches.push_back(std::make_pair(FD, ParamNum));
4627 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004628 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004629 // If the qualified name lookup yielded nothing, try typo correction
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004630 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004631 Prev.getLookupKind(), 0, 0,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004632 Validator, NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004633 // Trap errors.
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004634 Sema::SFINAETrap Trap(SemaRef);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004635
4636 // Set up everything for the call to ActOnFunctionDeclarator
4637 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4638 ExtraArgs.D.getIdentifierLoc());
4639 Previous.clear();
4640 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004641 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4642 CDeclEnd = Correction.end();
4643 CDecl != CDeclEnd; ++CDecl) {
4644 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004645 if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4646 MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004647 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004648 }
4649 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004650 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004651 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4652 // pieces need to verify the typo-corrected C++ declaraction and hopefully
4653 // eliminate the need for the parameter pack ExtraArgs.
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004654 Result = SemaRef.ActOnFunctionDeclarator(
4655 ExtraArgs.S, ExtraArgs.D,
4656 Correction.getCorrectionDecl()->getDeclContext(),
4657 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4658 ExtraArgs.AddToScope);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004659 if (Trap.hasErrorOccurred()) {
4660 // Pretend the typo correction never occurred
4661 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4662 ExtraArgs.D.getIdentifierLoc());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004663 ExtraArgs.D.setRedeclaration(wasRedeclaration);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004664 Previous.clear();
4665 Previous.setLookupName(Name);
4666 Result = NULL;
4667 } else {
4668 for (LookupResult::iterator Func = Previous.begin(),
4669 FuncEnd = Previous.end();
4670 Func != FuncEnd; ++Func) {
4671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4672 NearMatches.push_back(std::make_pair(FD, 0));
4673 }
4674 }
4675 if (NearMatches.empty()) {
4676 // Ignore the correction if it didn't yield any close FunctionDecl matches
4677 Correction = TypoCorrection();
4678 } else {
Kaelyn Uhrain7fbe2f72011-09-14 19:37:32 +00004679 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4680 : diag::err_member_def_does_not_match_suggest;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004681 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004682 }
4683
4684 if (Correction)
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004685 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004686 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004687 << FixItHint::CreateReplacement(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004688 NewFD->getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00004689 Correction.getAsString(SemaRef.getLangOpts()));
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004690 else
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004691 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4692 << Name << NewDC << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004693
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004694 bool NewFDisConst = false;
4695 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4696 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4697
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004698 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4699 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4700 NearMatch != NearMatchEnd; ++NearMatch) {
4701 FunctionDecl *FD = NearMatch->first;
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004702 bool FDisConst = false;
4703 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4704 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004705
4706 if (unsigned Idx = NearMatch->second) {
4707 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00004708 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
4709 if (Loc.isInvalid()) Loc = FD->getLocation();
4710 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004711 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4712 } else if (Correction) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004713 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004714 << Correction.getQuoted(SemaRef.getLangOpts());
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004715 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004716 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004717 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004718 } else
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004719 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00004720 }
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004721 return Result;
John McCallf7cfb222010-10-13 05:45:15 +00004722}
4723
David Blaikie30d15442011-10-19 22:56:21 +00004724static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
4725 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004726 switch (D.getDeclSpec().getStorageClassSpec()) {
4727 default: llvm_unreachable("Unknown storage class!");
4728 case DeclSpec::SCS_auto:
4729 case DeclSpec::SCS_register:
4730 case DeclSpec::SCS_mutable:
4731 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4732 diag::err_typecheck_sclass_func);
4733 D.setInvalidType();
4734 break;
4735 case DeclSpec::SCS_unspecified: break;
4736 case DeclSpec::SCS_extern: return SC_Extern;
4737 case DeclSpec::SCS_static: {
4738 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4739 // C99 6.7.1p5:
4740 // The declaration of an identifier for a function that has
4741 // block scope shall have no explicit storage-class specifier
4742 // other than extern
4743 // See also (C++ [dcl.stc]p4).
4744 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4745 diag::err_static_block_func);
4746 break;
4747 } else
4748 return SC_Static;
4749 }
4750 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4751 }
4752
4753 // No explicit storage class has already been returned
4754 return SC_None;
4755}
4756
4757static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4758 DeclContext *DC, QualType &R,
4759 TypeSourceInfo *TInfo,
4760 FunctionDecl::StorageClass SC,
4761 bool &IsVirtualOkay) {
4762 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4763 DeclarationName Name = NameInfo.getName();
4764
4765 FunctionDecl *NewFD = 0;
4766 bool isInline = D.getDeclSpec().isInlineSpecified();
4767 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4768 FunctionDecl::StorageClass SCAsWritten
4769 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4770
David Blaikiebbafb8a2012-03-11 07:00:24 +00004771 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004772 // Determine whether the function was written with a
4773 // prototype. This true when:
4774 // - there is a prototype in the declarator, or
4775 // - the type R of the function is some kind of typedef or other reference
4776 // to a type name (which eventually refers to a function type).
4777 bool HasPrototype =
4778 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4779 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4780
David Blaikie30d15442011-10-19 22:56:21 +00004781 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004782 D.getLocStart(), NameInfo, R,
David Blaikie30d15442011-10-19 22:56:21 +00004783 TInfo, SC, SCAsWritten, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004784 HasPrototype);
4785 if (D.isInvalidType())
4786 NewFD->setInvalidDecl();
4787
4788 // Set the lexical context.
4789 NewFD->setLexicalDeclContext(SemaRef.CurContext);
4790
4791 return NewFD;
4792 }
4793
4794 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4795 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4796
4797 // Check that the return type is not an abstract class type.
4798 // For record types, this is done by the AbstractClassUsageDiagnoser once
4799 // the class has been completely parsed.
4800 if (!DC->isRecord() &&
4801 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4802 R->getAs<FunctionType>()->getResultType(),
4803 diag::err_abstract_type_in_decl,
4804 SemaRef.AbstractReturnType))
4805 D.setInvalidType();
4806
4807 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4808 // This is a C++ constructor declaration.
4809 assert(DC->isRecord() &&
4810 "Constructors can only be declared in a member context");
4811
4812 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4813 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004814 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004815 R, TInfo, isExplicit, isInline,
4816 /*isImplicitlyDeclared=*/false,
4817 isConstexpr);
4818
4819 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4820 // This is a C++ destructor declaration.
4821 if (DC->isRecord()) {
4822 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4823 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4824 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4825 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004826 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004827 NameInfo, R, TInfo, isInline,
4828 /*isImplicitlyDeclared=*/false);
4829
4830 // If the class is complete, then we now create the implicit exception
4831 // specification. If the class is incomplete or dependent, we can't do
4832 // it yet.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004833 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004834 Record->getDefinition() && !Record->isBeingDefined() &&
4835 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4836 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4837 }
4838
4839 IsVirtualOkay = true;
4840 return NewDD;
4841
4842 } else {
4843 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4844 D.setInvalidType();
4845
4846 // Create a FunctionDecl to satisfy the function definition parsing
4847 // code path.
4848 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004849 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004850 D.getIdentifierLoc(), Name, R, TInfo,
4851 SC, SCAsWritten, isInline,
4852 /*hasPrototype=*/true, isConstexpr);
4853 }
4854
4855 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4856 if (!DC->isRecord()) {
4857 SemaRef.Diag(D.getIdentifierLoc(),
4858 diag::err_conv_function_not_member);
4859 return 0;
4860 }
4861
4862 SemaRef.CheckConversionDeclarator(D, R, SC);
4863 IsVirtualOkay = true;
4864 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004865 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004866 R, TInfo, isInline, isExplicit,
4867 isConstexpr, SourceLocation());
4868
4869 } else if (DC->isRecord()) {
4870 // If the name of the function is the same as the name of the record,
4871 // then this must be an invalid constructor that has a return type.
4872 // (The parser checks for a return type and makes the declarator a
4873 // constructor if it has no return type).
4874 if (Name.getAsIdentifierInfo() &&
4875 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4876 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4877 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4878 << SourceRange(D.getIdentifierLoc());
4879 return 0;
4880 }
4881
4882 bool isStatic = SC == SC_Static;
4883
4884 // [class.free]p1:
4885 // Any allocation function for a class T is a static member
4886 // (even if not explicitly declared static).
4887 if (Name.getCXXOverloadedOperator() == OO_New ||
4888 Name.getCXXOverloadedOperator() == OO_Array_New)
4889 isStatic = true;
4890
4891 // [class.free]p6 Any deallocation function for a class X is a static member
4892 // (even if not explicitly declared static).
4893 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4894 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4895 isStatic = true;
4896
4897 IsVirtualOkay = !isStatic;
4898
4899 // This is a C++ method declaration.
4900 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004901 D.getLocStart(), NameInfo, R,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004902 TInfo, isStatic, SCAsWritten, isInline,
4903 isConstexpr, SourceLocation());
4904
4905 } else {
4906 // Determine whether the function was written with a
4907 // prototype. This true when:
4908 // - we're in C++ (where every function has a prototype),
4909 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004910 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004911 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4912 true/*HasPrototype*/, isConstexpr);
4913 }
4914}
4915
Mike Stump11289f42009-09-09 15:08:12 +00004916NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00004917Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004918 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004919 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004920 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004921 QualType R = TInfo->getType();
4922
Zhongxing Xubece5d62009-01-16 01:13:29 +00004923 assert(R.getTypePtr()->isFunctionType());
4924
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004925 // TODO: consider using NameInfo for diagnostic.
4926 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4927 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004928 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004929
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004930 if (D.getDeclSpec().isThreadSpecified())
4931 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4932
Chris Lattner347eec92009-04-11 19:17:25 +00004933 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00004934 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00004935 Diag(D.getIdentifierLoc(),
4936 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004937 << R->getAs<FunctionType>()->getResultType()
4938 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004939
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004940 QualType T = R->getAs<FunctionType>()->getResultType();
4941 T = Context.getObjCObjectPointerType(T);
4942 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4943 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4944 R = Context.getFunctionType(T, FPT->arg_type_begin(),
4945 FPT->getNumArgs(), EPI);
4946 }
4947 else if (isa<FunctionNoProtoType>(R))
4948 R = Context.getFunctionNoProtoType(T);
Chris Lattner347eec92009-04-11 19:17:25 +00004949 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004950
Douglas Gregor513e63c2010-12-10 19:28:19 +00004951 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00004952 FunctionTemplateDecl *FunctionTemplate = 0;
4953 bool isExplicitSpecialization = false;
4954 bool isFunctionTemplateSpecialization = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004955 bool isDependentClassScopeExplicitSpecialization = false;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004956 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004957
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004958 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4959 isVirtualOkay);
4960 if (!NewFD) return 0;
4961
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004962 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4963 NewFD->setTopLevelDeclInObjCContainer();
4964
David Blaikiebbafb8a2012-03-11 07:00:24 +00004965 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004966 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004967 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4968 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00004969 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004970 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004971 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00004972 // C++ [class.friend]p5
4973 // A function can be defined in a friend declaration of a
4974 // class . . . . Such a function is implicitly inline.
4975 NewFD->setImplicitlyInline();
4976 }
4977
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004978 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004979 isExplicitSpecialization = false;
4980 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004981 if (D.isInvalidType())
4982 NewFD->setInvalidDecl();
4983
4984 // Set the lexical context. If the declarator has a C++
4985 // scope specifier, or is the object of a friend declaration, the
4986 // lexical context will be different from the semantic context.
4987 NewFD->setLexicalDeclContext(CurContext);
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004988
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004989 // Match up the template parameter lists with the scope specifier, then
4990 // determine whether we have a template or a template specialization.
4991 bool Invalid = false;
4992 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00004993 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004994 D.getDeclSpec().getLocStart(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004995 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00004996 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00004997 TemplateParamLists.get(),
4998 TemplateParamLists.size(),
4999 isFriend,
5000 isExplicitSpecialization,
5001 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00005002 if (TemplateParams->size() > 0) {
5003 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005004
Abramo Bagnara60804e12011-03-18 15:16:37 +00005005 // Check that we can declare a template here.
5006 if (CheckTemplateDeclScope(S, TemplateParams))
5007 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005008
Abramo Bagnara60804e12011-03-18 15:16:37 +00005009 // A destructor cannot be a template.
5010 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5011 Diag(NewFD->getLocation(), diag::err_destructor_template);
5012 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00005013 }
Douglas Gregor041b0842011-10-14 15:31:12 +00005014
5015 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00005016 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00005017 // now that we know what the current instantiation is.
5018 if (DC->isDependentContext()) {
5019 ContextRAII SavedContext(*this, DC);
5020 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5021 Invalid = true;
5022 }
5023
John McCall1f0479e2010-03-24 08:27:58 +00005024
Abramo Bagnara60804e12011-03-18 15:16:37 +00005025 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5026 NewFD->getLocation(),
5027 Name, TemplateParams,
5028 NewFD);
5029 FunctionTemplate->setLexicalDeclContext(CurContext);
5030 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5031
5032 // For source fidelity, store the other template param lists.
5033 if (TemplateParamLists.size() > 1) {
5034 NewFD->setTemplateParameterListsInfo(Context,
5035 TemplateParamLists.size() - 1,
5036 TemplateParamLists.release());
5037 }
5038 } else {
5039 // This is a function template specialization.
5040 isFunctionTemplateSpecialization = true;
5041 // For source fidelity, store all the template param lists.
5042 NewFD->setTemplateParameterListsInfo(Context,
5043 TemplateParamLists.size(),
5044 TemplateParamLists.release());
5045
5046 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5047 if (isFriend) {
5048 // We want to remove the "template<>", found here.
5049 SourceRange RemoveRange = TemplateParams->getSourceRange();
5050
5051 // If we remove the template<> and the name is not a
5052 // template-id, we're actually silently creating a problem:
5053 // the friend declaration will refer to an untemplated decl,
5054 // and clearly the user wants a template specialization. So
5055 // we need to insert '<>' after the name.
5056 SourceLocation InsertLoc;
5057 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5058 InsertLoc = D.getName().getSourceRange().getEnd();
5059 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5060 }
5061
5062 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5063 << Name << RemoveRange
5064 << FixItHint::CreateRemoval(RemoveRange)
5065 << FixItHint::CreateInsertion(InsertLoc, "<>");
5066 }
5067 }
5068 }
5069 else {
5070 // All template param lists were matched against the scope specifier:
5071 // this is NOT (an explicit specialization of) a template.
5072 if (TemplateParamLists.size() > 0)
5073 // For source fidelity, store all the template param lists.
5074 NewFD->setTemplateParameterListsInfo(Context,
5075 TemplateParamLists.size(),
5076 TemplateParamLists.release());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005077 }
5078
5079 if (Invalid) {
5080 NewFD->setInvalidDecl();
5081 if (FunctionTemplate)
5082 FunctionTemplate->setInvalidDecl();
5083 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005084
Richard Smithd069d2f2012-01-06 01:31:20 +00005085 // If we see "T var();" at block scope, where T is a class type, it is
5086 // probably an attempt to initialize a variable, not a function declaration.
5087 // We don't catch this case earlier, since there is no ambiguity here.
5088 if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
5089 CurContext->isFunctionOrMethod() &&
5090 D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
5091 D.getDeclSpec().getStorageClassSpecAsWritten()
5092 == DeclSpec::SCS_unspecified) {
5093 QualType T = R->getAs<FunctionType>()->getResultType();
5094 DeclaratorChunk &C = D.getTypeObject(0);
Richard Smithb3851f52012-01-06 02:30:50 +00005095 if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
Richard Smithd069d2f2012-01-06 01:31:20 +00005096 !C.Fun.TrailingReturnType &&
5097 C.Fun.getExceptionSpecType() == EST_None) {
Richard Smith8d06f422012-01-12 23:53:29 +00005098 SourceRange ParenRange(C.Loc, C.EndLoc);
5099 Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5100
5101 // If the declaration looks like:
5102 // T var1,
5103 // f();
5104 // and name lookup finds a function named 'f', then the ',' was
5105 // probably intended to be a ';'.
5106 if (!D.isFirstDeclarator() && D.getIdentifier()) {
5107 FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5108 FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5109 if (Comma.getFileID() != Name.getFileID() ||
5110 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5111 LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5112 LookupOrdinaryName);
5113 if (LookupName(Result, S))
5114 Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5115 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5116 }
5117 }
5118 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5119 // Empty parens mean value-initialization, and no parens mean default
5120 // initialization. These are equivalent if the default constructor is
5121 // user-provided, or if zero-initialization is a no-op.
Richard Smith90b748e2012-01-13 02:14:39 +00005122 if (RD && RD->hasDefinition() &&
5123 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
Richard Smith8d06f422012-01-12 23:53:29 +00005124 Diag(C.Loc, diag::note_empty_parens_default_ctor)
5125 << FixItHint::CreateRemoval(ParenRange);
David Blaikie7665a622012-04-30 18:27:22 +00005126 else {
5127 std::string Init = getFixItZeroInitializerForType(T);
5128 if (Init.empty() && LangOpts.CPlusPlus0x)
5129 Init = "{}";
5130 if (!Init.empty())
5131 Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5132 << FixItHint::CreateReplacement(ParenRange, Init);
5133 }
Richard Smithd069d2f2012-01-06 01:31:20 +00005134 }
5135 }
5136
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005137 // C++ [dcl.fct.spec]p5:
5138 // The virtual specifier shall only be used in declarations of
5139 // nonstatic class member functions that appear within a
5140 // member-specification of a class declaration; see 10.3.
5141 //
5142 if (isVirtual && !NewFD->isInvalidDecl()) {
5143 if (!isVirtualOkay) {
5144 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5145 diag::err_virtual_non_function);
5146 } else if (!CurContext->isRecord()) {
5147 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00005148 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5149 diag::err_virtual_out_of_class)
5150 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5151 } else if (NewFD->getDescribedFunctionTemplate()) {
5152 // C++ [temp.mem]p3:
5153 // A member function template shall not be virtual.
5154 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5155 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005156 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5157 } else {
5158 // Okay: Add virtual to the method.
5159 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00005160 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00005161 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005162
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005163 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00005164 // The inline specifier shall not appear on a block scope function
5165 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005166 if (isInline && !NewFD->isInvalidDecl()) {
5167 if (CurContext->isFunctionOrMethod()) {
5168 // 'inline' is not allowed on block scope function declaration.
5169 Diag(D.getDeclSpec().getInlineSpecLoc(),
5170 diag::err_inline_declaration_block_scope) << Name
5171 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5172 }
5173 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005174
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005175 // C++ [dcl.fct.spec]p6:
5176 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00005177 // constructor or conversion function within its class definition;
5178 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005179 if (isExplicit && !NewFD->isInvalidDecl()) {
5180 if (!CurContext->isRecord()) {
5181 // 'explicit' was specified outside of the class.
5182 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5183 diag::err_explicit_out_of_class)
5184 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5185 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5186 !isa<CXXConversionDecl>(NewFD)) {
5187 // 'explicit' was specified on a function that wasn't a constructor
5188 // or conversion function.
5189 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5190 diag::err_explicit_non_ctor_or_conv_function)
5191 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5192 }
5193 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005194
Richard Smitha77a0a62011-08-15 21:04:07 +00005195 if (isConstexpr) {
5196 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5197 // are implicitly inline.
5198 NewFD->setImplicitlyInline();
5199
Richard Smitha77a0a62011-08-15 21:04:07 +00005200 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5201 // be either constructors or to return a literal type. Therefore,
5202 // destructors cannot be declared constexpr.
5203 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00005204 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00005205 }
5206
Douglas Gregor26701a42011-09-09 02:06:17 +00005207 // If __module_private__ was specified, mark the function accordingly.
5208 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005209 if (isFunctionTemplateSpecialization) {
5210 SourceLocation ModulePrivateLoc
5211 = D.getDeclSpec().getModulePrivateSpecLoc();
5212 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5213 << 0
5214 << FixItHint::CreateRemoval(ModulePrivateLoc);
5215 } else {
5216 NewFD->setModulePrivate();
5217 if (FunctionTemplate)
5218 FunctionTemplate->setModulePrivate();
5219 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005220 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005221
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005222 if (isFriend) {
5223 // For now, claim that the objects have no previous declaration.
5224 if (FunctionTemplate) {
5225 FunctionTemplate->setObjectOfFriendDecl(false);
5226 FunctionTemplate->setAccess(AS_public);
5227 }
5228 NewFD->setObjectOfFriendDecl(false);
5229 NewFD->setAccess(AS_public);
5230 }
5231
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005232 // If a function is defined as defaulted or deleted, mark it as such now.
5233 switch (D.getFunctionDefinitionKind()) {
5234 case FDK_Declaration:
5235 case FDK_Definition:
5236 break;
5237
5238 case FDK_Defaulted:
5239 NewFD->setDefaulted();
5240 break;
5241
5242 case FDK_Deleted:
5243 NewFD->setDeletedAsWritten();
5244 break;
5245 }
5246
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005247 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5248 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005249 // C++ [class.mfct]p2:
5250 // A member function may be defined (8.4) in its class definition, in
5251 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00005252 NewFD->setImplicitlyInline();
5253 }
5254
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005255 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5256 !CurContext->isRecord()) {
5257 // C++ [class.static]p1:
5258 // A data or function member of a class may be declared static
5259 // in a class definition, in which case it is a static member of
5260 // the class.
5261
5262 // Complain about the 'static' specifier if it's on an out-of-line
5263 // member function definition.
5264 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5265 diag::err_static_out_of_line)
5266 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5267 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005268 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005269
5270 // Filter out previous declarations that don't match the scope.
5271 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5272 isExplicitSpecialization ||
5273 isFunctionTemplateSpecialization);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005274
Zhongxing Xubece5d62009-01-16 01:13:29 +00005275 // Handle GNU asm-label extension (encoded as an attribute).
5276 if (Expr *E = (Expr*) D.getAsmLabel()) {
5277 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005278 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005279 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5280 SE->getString()));
David Chisnall0867d9c2012-02-18 16:12:34 +00005281 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5282 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5283 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5284 if (I != ExtnameUndeclaredIdentifiers.end()) {
5285 NewFD->addAttr(I->second);
5286 ExtnameUndeclaredIdentifiers.erase(I);
5287 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005288 }
5289
Chris Lattner9af40c12009-04-25 06:12:16 +00005290 // Copy the parameter declarations from the declarator D to the function
5291 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005292 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00005293 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005294 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00005295
Zhongxing Xubece5d62009-01-16 01:13:29 +00005296 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5297 // function that takes no arguments, not a function that takes a
5298 // single void argument.
5299 // We let through "const void" here because Sema::GetTypeForDeclarator
5300 // already checks for that case.
5301 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5302 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005303 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00005304 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00005305 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005306
5307 // In C++, the empty parameter-type-list must be spelled "void"; a
5308 // typedef of void is not permitted.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005309 if (getLangOpts().CPlusPlus &&
Richard Smithdda56e42011-04-15 14:24:37 +00005310 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5311 bool IsTypeAlias = false;
5312 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5313 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005314 else if (const TemplateSpecializationType *TST =
5315 Param->getType()->getAs<TemplateSpecializationType>())
5316 IsTypeAlias = TST->isTypeAlias();
Richard Smithdda56e42011-04-15 14:24:37 +00005317 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5318 << IsTypeAlias;
5319 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005320 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005321 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00005322 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005323 assert(Param->getDeclContext() != NewFD && "Was set before ?");
5324 Param->setDeclContext(NewFD);
5325 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00005326
5327 if (Param->isInvalidDecl())
5328 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005329 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005330 }
Mike Stump11289f42009-09-09 15:08:12 +00005331
John McCall9dd450b2009-09-21 23:43:11 +00005332 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00005333 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00005334 // following example, we'll need to synthesize (unnamed)
5335 // parameters for use in the declaration.
5336 //
5337 // @code
5338 // typedef void fn(int);
5339 // fn f;
5340 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005341
Chris Lattner47c0d002009-04-25 06:03:53 +00005342 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00005343 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5344 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00005345 ParmVarDecl *Param =
5346 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00005347 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00005348 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005349 }
Chris Lattner49303b22009-04-25 18:38:18 +00005350 } else {
5351 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5352 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00005353 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005354
Chris Lattner9af40c12009-04-25 06:12:16 +00005355 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00005356 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00005357
James Molloy6f8780b2012-02-29 10:24:19 +00005358 // Find all anonymous symbols defined during the declaration of this function
5359 // and add to NewFD. This lets us track decls such 'enum Y' in:
5360 //
5361 // void f(enum Y {AA} x) {}
5362 //
5363 // which would otherwise incorrectly end up in the translation unit scope.
5364 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5365 DeclsInPrototypeScope.clear();
5366
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005367 // Process the non-inheritable attributes on this declaration.
5368 ProcessDeclAttributes(S, NewFD, D,
5369 /*NonInheritable=*/true, /*Inheritable=*/false);
5370
Richard Smith84208dc2012-03-13 05:56:40 +00005371 // Functions returning a variably modified type violate C99 6.7.5.2p2
5372 // because all functions have linkage.
5373 if (!NewFD->isInvalidDecl() &&
5374 NewFD->getResultType()->isVariablyModifiedType()) {
5375 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5376 NewFD->setInvalidDecl();
5377 }
5378
David Blaikiebbafb8a2012-03-11 07:00:24 +00005379 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005380 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00005381 bool isExplicitSpecialization=false;
David Blaikied937bf12011-09-08 06:33:04 +00005382 if (!NewFD->isInvalidDecl()) {
Richard Smith84208dc2012-03-13 05:56:40 +00005383 if (NewFD->isMain())
5384 CheckMain(NewFD, D.getDeclSpec());
5385 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5386 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00005387 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005388 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005389 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5390 "previous declaration set still overloaded");
5391 } else {
5392 // If the declarator is a template-id, translate the parser's template
5393 // argument list into our AST format.
5394 bool HasExplicitTemplateArgs = false;
5395 TemplateArgumentListInfo TemplateArgs;
5396 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5397 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5398 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5399 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5400 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5401 TemplateId->getTemplateArgs(),
5402 TemplateId->NumArgs);
5403 translateTemplateArguments(TemplateArgsPtr,
5404 TemplateArgs);
5405 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00005406
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005407 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00005408
Douglas Gregor522d5eb2011-06-06 15:22:55 +00005409 if (NewFD->isInvalidDecl()) {
5410 HasExplicitTemplateArgs = false;
5411 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00005412 // Function template with explicit template arguments.
5413 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5414 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5415
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005416 HasExplicitTemplateArgs = false;
5417 } else if (!isFunctionTemplateSpecialization &&
5418 !D.getDeclSpec().isFriendSpecified()) {
5419 // We have encountered something that the user meant to be a
5420 // specialization (because it has explicitly-specified template
5421 // arguments) but that was not introduced with a "template<>" (or had
5422 // too few of them).
5423 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5424 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5425 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005426 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00005427 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005428 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00005429 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005430 // "friend void foo<>(int);" is an implicit specialization decl.
5431 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00005432 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005433 } else if (isFriend && isFunctionTemplateSpecialization) {
5434 // This combination is only possible in a recovery case; the user
5435 // wrote something like:
5436 // template <> friend void foo(int);
5437 // which we're recovering from as if the user had written:
5438 // friend void foo<>(int);
5439 // Go ahead and fake up a template id.
5440 HasExplicitTemplateArgs = true;
5441 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5442 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005443 }
John McCallf7cfb222010-10-13 05:45:15 +00005444
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005445 // If it's a friend (and only if it's a friend), it's possible
5446 // that either the specialized function type or the specialized
5447 // template is dependent, and therefore matching will fail. In
5448 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00005449 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005450 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00005451 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5452 TemplateSpecializationType::anyDependentTemplateArguments(
5453 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5454 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005455 assert(HasExplicitTemplateArgs &&
5456 "friend function specialization without template args");
5457 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5458 Previous))
5459 NewFD->setInvalidDecl();
5460 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00005461 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00005462 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005463 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005464 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005465 diag::ext_function_specialization_in_class :
5466 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00005467 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00005468 } else if (CheckFunctionTemplateSpecialization(NewFD,
5469 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5470 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005471 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00005472
5473 // C++ [dcl.stc]p1:
5474 // A storage-class-specifier shall not be specified in an explicit
5475 // specialization (14.7.3)
5476 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00005477 if (SC != NewFD->getStorageClass())
5478 Diag(NewFD->getLocation(),
5479 diag::err_explicit_specialization_inconsistent_storage_class)
5480 << SC
5481 << FixItHint::CreateRemoval(
5482 D.getDeclSpec().getStorageClassSpecLoc());
5483
5484 else
5485 Diag(NewFD->getLocation(),
5486 diag::ext_explicit_specialization_storage_class)
5487 << FixItHint::CreateRemoval(
5488 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00005489 }
5490
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005491 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5492 if (CheckMemberSpecialization(NewFD, Previous))
5493 NewFD->setInvalidDecl();
5494 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005495
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005496 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00005497 if (!isDependentClassScopeExplicitSpecialization) {
5498 if (NewFD->isInvalidDecl()) {
5499 // If this is a class member, mark the class invalid immediately.
5500 // This avoids some consistency errors later.
5501 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5502 methodDecl->getParent()->setInvalidDecl();
5503 } else {
5504 if (NewFD->isMain())
5505 CheckMain(NewFD, D.getDeclSpec());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005506 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5507 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00005508 }
5509 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005510
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005511 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005512 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5513 "previous declaration set still overloaded");
5514
5515 NamedDecl *PrincipalDecl = (FunctionTemplate
5516 ? cast<NamedDecl>(FunctionTemplate)
5517 : NewFD);
5518
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005519 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005520 AccessSpecifier Access = AS_public;
5521 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00005522 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005523
5524 NewFD->setAccess(Access);
5525 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5526
5527 PrincipalDecl->setObjectOfFriendDecl(true);
5528 }
5529
5530 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5531 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5532 PrincipalDecl->setNonMemberOperator();
5533
5534 // If we have a function template, check the template parameter
5535 // list. This will check and merge default template arguments.
5536 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00005537 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00005538 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005539 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00005540 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005541 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005542 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005543 ? TPC_FriendFunctionTemplateDefinition
5544 : TPC_FriendFunctionTemplate)
5545 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00005546 DC && DC->isRecord() &&
5547 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005548 ? TPC_ClassTemplateMember
5549 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005550 }
5551
5552 if (NewFD->isInvalidDecl()) {
5553 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005554 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005555 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005556 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005557 // Fake up an access specifier if it's supposed to be a class member.
5558 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5559 NewFD->setAccess(AS_public);
5560
5561 // Qualified decls generally require a previous declaration.
5562 if (D.getCXXScopeSpec().isSet()) {
5563 // ...with the major exception of templated-scope or
5564 // dependent-scope friend declarations.
5565
5566 // TODO: we currently also suppress this check in dependent
5567 // contexts because (1) the parameter depth will be off when
5568 // matching friend templates and (2) we might actually be
5569 // selecting a friend based on a dependent factor. But there
5570 // are situations where these conditions don't apply and we
5571 // can actually do this check immediately.
5572 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00005573 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005574 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5575 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005576 // ignore these
5577 } else {
5578 // The user tried to provide an out-of-line definition for a
5579 // function that is a member of a class or namespace, but there
5580 // was no such member function declared (C++ [class.mfct]p2,
5581 // C++ [namespace.memdef]p2). For example:
5582 //
5583 // class X {
5584 // void f() const;
5585 // };
5586 //
5587 // void X::f() { } // ill-formed
5588 //
5589 // Complain about this problem, and attempt to suggest close
5590 // matches (e.g., those that differ only in cv-qualifiers and
5591 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005592
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005593 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005594 NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005595 ExtraArgs)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005596 AddToScope = ExtraArgs.AddToScope;
5597 return Result;
5598 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005599 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005600
5601 // Unqualified local friend declarations are required to resolve
5602 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005603 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005604 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005605 NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005606 ExtraArgs)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005607 AddToScope = ExtraArgs.AddToScope;
5608 return Result;
5609 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005610 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005611
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005612 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005613 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00005614 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005615 // An out-of-line member function declaration must also be a
5616 // definition (C++ [dcl.meaning]p1).
5617 // Note that this is not the case for explicit specializations of
5618 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00005619 // C++ [temp.expl.spec]p2. We also allow these declarations as an
5620 // extension for compatibility with old SWIG code which likes to
5621 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005622 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5623 << D.getCXXScopeSpec().getRange();
5624 }
5625 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +00005626
5627
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005628 // Handle attributes. We need to have merged decls when handling attributes
5629 // (for example to check for conflicts, etc).
5630 // FIXME: This needs to happen before we merge declarations. Then,
5631 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005632 ProcessDeclAttributes(S, NewFD, D,
5633 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00005634
5635 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005636 // FIXME: This should happen during attribute merging
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005637 if (D.isRedeclaration() && Previous.isSingleResult()) {
John McCall1f82f242009-11-18 22:49:29 +00005638 const FunctionDecl *Def;
5639 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005640 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00005641 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5642 Diag(Def->getLocation(), diag::note_previous_definition);
5643 }
5644 }
5645
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005646 AddKnownFunctionAttributes(NewFD);
5647
Douglas Gregor72609052010-08-06 13:50:58 +00005648 if (NewFD->hasAttr<OverloadableAttr>() &&
5649 !NewFD->getType()->getAs<FunctionProtoType>()) {
5650 Diag(NewFD->getLocation(),
5651 diag::err_attribute_overloadable_no_prototype)
5652 << NewFD;
5653
5654 // Turn this into a variadic function with no parameters.
5655 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005656 FunctionProtoType::ExtProtoInfo EPI;
5657 EPI.Variadic = true;
5658 EPI.ExtInfo = FT->getExtInfo();
5659
5660 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00005661 NewFD->setType(R);
5662 }
5663
Eli Friedman570024a2010-08-05 06:57:20 +00005664 // If there's a #pragma GCC visibility in scope, and this isn't a class
5665 // member, set the visibility of this function.
5666 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5667 AddPushedVisibilityAttribute(NewFD);
5668
John McCall32f5fe12011-09-30 05:12:12 +00005669 // If there's a #pragma clang arc_cf_code_audited in scope, consider
5670 // marking the function.
5671 AddCFAuditedAttribute(NewFD);
5672
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005673 // If this is a locally-scoped extern C function, update the
5674 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00005675 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005676 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00005677 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005678
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00005679 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00005680 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00005681
David Blaikiebbafb8a2012-03-11 07:00:24 +00005682 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005683 if (FunctionTemplate) {
5684 if (NewFD->isInvalidDecl())
5685 FunctionTemplate->setInvalidDecl();
5686 return FunctionTemplate;
5687 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005688 }
Mike Stump11289f42009-09-09 15:08:12 +00005689
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005690 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005691
David Blaikiebbafb8a2012-03-11 07:00:24 +00005692 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005693 if (IdentifierInfo *II = NewFD->getIdentifier())
5694 if (!NewFD->isInvalidDecl() &&
5695 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5696 if (II->isStr("cudaConfigureCall")) {
5697 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5698 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5699
5700 Context.setcudaConfigureCallDecl(NewFD);
5701 }
5702 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005703
5704 // Here we have an function template explicit specialization at class scope.
5705 // The actually specialization will be postponed to template instatiation
5706 // time via the ClassScopeFunctionSpecializationDecl node.
5707 if (isDependentClassScopeExplicitSpecialization) {
5708 ClassScopeFunctionSpecializationDecl *NewSpec =
5709 ClassScopeFunctionSpecializationDecl::Create(
5710 Context, CurContext, SourceLocation(),
5711 cast<CXXMethodDecl>(NewFD));
5712 CurContext->addDecl(NewSpec);
5713 AddToScope = false;
5714 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005715
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005716 return NewFD;
5717}
5718
5719/// \brief Perform semantic checking of a new function declaration.
5720///
5721/// Performs semantic analysis of the new function declaration
5722/// NewFD. This routine performs all semantic checking that does not
5723/// require the actual declarator involved in the declaration, and is
5724/// used both for the declaration of functions as they are parsed
5725/// (called via ActOnDeclarator) and for the declaration of functions
5726/// that have been instantiated via C++ template instantiation (called
5727/// via InstantiateDecl).
5728///
Douglas Gregorcf915552009-10-13 16:30:37 +00005729/// \param IsExplicitSpecialiation whether this new function declaration is
5730/// an explicit specialization of the previous declaration.
5731///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005732/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005733///
5734/// Returns true if the function declaration is a redeclaration.
5735bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00005736 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005737 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00005738 assert(!NewFD->getResultType()->isVariablyModifiedType()
5739 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00005740
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005741 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00005742 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005743 // Since we did not find anything by this name and we're declaring
5744 // an extern "C" function, look for a non-visible extern "C"
5745 // declaration with the same name.
5746 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00005747 = findLocallyScopedExternalDecl(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005748 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00005749 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005750 }
5751
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005752 bool Redeclaration = false;
5753
Douglas Gregore62c0a42009-02-24 01:23:02 +00005754 // Merge or overload the declaration with an existing declaration of
5755 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00005756 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00005757 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00005758 // a declaration that requires merging. If it's an overload,
5759 // there's no more work to do here; we'll just add the new
5760 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00005761
John McCall1f82f242009-11-18 22:49:29 +00005762 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00005763 if (!AllowOverloadingOfFunction(Previous, Context)) {
5764 Redeclaration = true;
5765 OldDecl = Previous.getFoundDecl();
5766 } else {
John McCalle9cccd82010-06-16 08:42:20 +00005767 switch (CheckOverload(S, NewFD, Previous, OldDecl,
5768 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00005769 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005770 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00005771 break;
5772
5773 case Ovl_NonFunction:
5774 Redeclaration = true;
5775 break;
5776
5777 case Ovl_Overload:
5778 Redeclaration = false;
5779 break;
John McCall1f82f242009-11-18 22:49:29 +00005780 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005781
David Blaikiebbafb8a2012-03-11 07:00:24 +00005782 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005783 // If a function name is overloadable in C, then every function
5784 // with that name must be marked "overloadable".
5785 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5786 << Redeclaration << NewFD;
5787 NamedDecl *OverloadedDecl = 0;
5788 if (Redeclaration)
5789 OverloadedDecl = OldDecl;
5790 else if (!Previous.empty())
5791 OverloadedDecl = Previous.getRepresentativeDecl();
5792 if (OverloadedDecl)
5793 Diag(OverloadedDecl->getLocation(),
5794 diag::note_attribute_overloadable_prev_overload);
5795 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5796 Context));
5797 }
John McCall1f82f242009-11-18 22:49:29 +00005798 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005799
John McCall1f82f242009-11-18 22:49:29 +00005800 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005801 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00005802 // merged.
James Molloye9430032012-03-13 08:55:35 +00005803 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005804 NewFD->setInvalidDecl();
5805 return Redeclaration;
5806 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005807
John McCall1f82f242009-11-18 22:49:29 +00005808 Previous.clear();
5809 Previous.addDecl(OldDecl);
5810
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005811 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00005812 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
David Blaikie30d15442011-10-19 22:56:21 +00005813 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00005814 FunctionTemplateDecl *NewTemplateDecl
5815 = NewFD->getDescribedFunctionTemplate();
5816 assert(NewTemplateDecl && "Template/non-template mismatch");
5817 if (CXXMethodDecl *Method
5818 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5819 Method->setAccess(OldTemplateDecl->getAccess());
5820 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5821 }
Douglas Gregorcf915552009-10-13 16:30:37 +00005822
5823 // If this is an explicit specialization of a member that is a function
5824 // template, mark it as a member specialization.
5825 if (IsExplicitSpecialization &&
5826 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5827 NewTemplateDecl->setMemberSpecialization();
5828 assert(OldTemplateDecl->isMemberSpecialization());
5829 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00005830
Douglas Gregorca027af2009-10-12 22:27:17 +00005831 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005832 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5833 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005834 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005835 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005836 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00005837 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005838
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005839 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00005840 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005841 // C++-specific checks.
5842 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5843 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005844 } else if (CXXDestructorDecl *Destructor =
5845 dyn_cast<CXXDestructorDecl>(NewFD)) {
5846 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005847 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005848
Douglas Gregor7454c562010-07-02 20:37:36 +00005849 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00005850 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005851 if (!ClassType->isDependentType()) {
5852 DeclarationName Name
5853 = Context.DeclarationNames.getCXXDestructorName(
5854 Context.getCanonicalType(ClassType));
5855 if (NewFD->getDeclName() != Name) {
5856 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005857 NewFD->setInvalidDecl();
5858 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005859 }
5860 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005861 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00005862 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005863 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00005864 }
5865
5866 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00005867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5868 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005869 !Method->getDescribedFunctionTemplate()) {
5870 if (AddOverriddenMethods(Method->getParent(), Method)) {
5871 // If the function was marked as "static", we have a problem.
5872 if (NewFD->getStorageClass() == SC_Static) {
5873 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5874 << NewFD->getDeclName();
5875 for (CXXMethodDecl::method_iterator
5876 Overridden = Method->begin_overridden_methods(),
5877 OverriddenEnd = Method->end_overridden_methods();
5878 Overridden != OverriddenEnd;
5879 ++Overridden) {
5880 Diag((*Overridden)->getLocation(),
5881 diag::note_overridden_virtual_function);
5882 }
5883 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005884 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005885 }
Douglas Gregor3024f072012-04-16 07:05:22 +00005886
5887 if (Method->isStatic())
5888 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00005889 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005890
5891 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5892 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005893 CheckOverloadedOperatorDeclaration(NewFD)) {
5894 NewFD->setInvalidDecl();
5895 return Redeclaration;
5896 }
Alexis Huntc88db062010-01-13 09:01:02 +00005897
5898 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5899 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005900 CheckLiteralOperatorDeclaration(NewFD)) {
5901 NewFD->setInvalidDecl();
5902 return Redeclaration;
5903 }
Alexis Huntc88db062010-01-13 09:01:02 +00005904
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005905 // In C++, check default arguments now that we have merged decls. Unless
5906 // the lexical context is the class, because in this case this is done
5907 // during delayed parsing anyway.
5908 if (!CurContext->isRecord())
5909 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00005910
5911 // If this function declares a builtin function, check the type of this
5912 // declaration against the expected type for the builtin.
5913 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5914 ASTContext::GetBuiltinTypeError Error;
5915 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5916 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5917 // The type of this function differs from the type of the builtin,
5918 // so forget about the builtin entirely.
5919 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5920 }
5921 }
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00005922
5923 // If this function is declared as being extern "C", then check to see if
5924 // the function returns a UDT (class, struct, or union type) that is not C
5925 // compatible, and if it does, warn the user.
5926 if (NewFD->isExternC()) {
5927 QualType R = NewFD->getResultType();
5928 if (!R.isPODType(Context) &&
5929 !R->isVoidType())
5930 Diag( NewFD->getLocation(), diag::warn_return_value_udt )
5931 << NewFD << R;
5932 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005933 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005934 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00005935}
5936
David Blaikied937bf12011-09-08 06:33:04 +00005937void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00005938 // C++11 [basic.start.main]p3: A program that declares main to be inline,
5939 // static or constexpr is ill-formed.
John McCall02dee0a2009-07-25 04:36:53 +00005940 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5941 // shall not appear in a declaration of main.
5942 // static main is not an error under C99, but we should warn about it.
David Blaikied937bf12011-09-08 06:33:04 +00005943 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005944 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00005945 ? diag::err_static_main : diag::warn_static_main)
5946 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5947 if (FD->isInlineSpecified())
5948 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5949 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Richard Smith3f333f22012-02-04 06:10:17 +00005950 if (FD->isConstexpr()) {
5951 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
5952 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
5953 FD->setConstexpr(false);
5954 }
John McCall02dee0a2009-07-25 04:36:53 +00005955
5956 QualType T = FD->getType();
5957 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00005958 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00005959
John McCall5ed3caf2012-02-14 19:50:52 +00005960 // All the standards say that main() should should return 'int'.
5961 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5962 // In C and C++, main magically returns 0 if you fall off the end;
5963 // set the flag which tells us that.
5964 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5965 FD->setHasImplicitReturnZero(true);
5966
5967 // In C with GNU extensions we allow main() to have non-integer return
5968 // type, but we should warn about the extension, and we disable the
5969 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005970 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00005971 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
5972
5973 // Otherwise, this is just a flat-out error.
5974 } else {
Douglas Gregorf05c0952011-02-19 19:04:23 +00005975 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00005976 FD->setInvalidDecl(true);
5977 }
5978
5979 // Treat protoless main() as nullary.
5980 if (isa<FunctionNoProtoType>(FT)) return;
5981
5982 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5983 unsigned nparams = FTP->getNumArgs();
5984 assert(FD->getNumParams() == nparams);
5985
John McCall0e21fcc2009-12-24 09:58:38 +00005986 bool HasExtraParameters = (nparams > 3);
5987
5988 // Darwin passes an undocumented fourth argument of type char**. If
5989 // other platforms start sprouting these, the logic below will start
5990 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00005991 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00005992 HasExtraParameters = false;
5993
5994 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00005995 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5996 FD->setInvalidDecl(true);
5997 nparams = 3;
5998 }
5999
6000 // FIXME: a lot of the following diagnostics would be improved
6001 // if we had some location information about types.
6002
6003 QualType CharPP =
6004 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00006005 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00006006
6007 for (unsigned i = 0; i < nparams; ++i) {
6008 QualType AT = FTP->getArgType(i);
6009
6010 bool mismatch = true;
6011
6012 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6013 mismatch = false;
6014 else if (Expected[i] == CharPP) {
6015 // As an extension, the following forms are okay:
6016 // char const **
6017 // char const * const *
6018 // char * const *
6019
John McCall8ccfcb52009-09-24 19:53:00 +00006020 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00006021 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006022 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6023 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00006024 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6025 qs.removeConst();
6026 mismatch = !qs.empty();
6027 }
6028 }
6029
6030 if (mismatch) {
6031 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6032 // TODO: suggest replacing given type with expected type
6033 FD->setInvalidDecl(true);
6034 }
6035 }
6036
6037 if (nparams == 1 && !FD->isInvalidDecl()) {
6038 Diag(FD->getLocation(), diag::warn_main_one_arg);
6039 }
Douglas Gregorbff62032010-10-21 16:57:46 +00006040
6041 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6042 Diag(FD->getLocation(), diag::err_main_template_decl);
6043 FD->setInvalidDecl();
6044 }
John McCalld9baf6a2009-07-24 03:03:21 +00006045}
6046
Eli Friedmand5a55bd2008-05-20 13:48:25 +00006047bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00006048 // FIXME: Need strict checking. In C89, we need to check for
6049 // any assignment, increment, decrement, function-calls, or
6050 // commas outside of a sizeof. In C99, it's the same list,
6051 // except that the aforementioned are allowed in unevaluated
6052 // expressions. Everything else falls under the
6053 // "may accept other forms of constant expressions" exception.
6054 // (We never end up here for C++, so the constant expression
6055 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00006056 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00006057 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00006058 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6059 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00006060 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00006061}
6062
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006063namespace {
6064 // Visits an initialization expression to see if OrigDecl is evaluated in
6065 // its own initialization and throws a warning if it does.
6066 class SelfReferenceChecker
6067 : public EvaluatedExprVisitor<SelfReferenceChecker> {
6068 Sema &S;
6069 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006070 bool isRecordType;
6071 bool isPODType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006072
6073 public:
6074 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6075
6076 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00006077 S(S), OrigDecl(OrigDecl) {
6078 isPODType = false;
6079 isRecordType = false;
6080 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6081 isPODType = VD->getType().isPODType(S.Context);
6082 isRecordType = VD->getType()->isRecordType();
6083 }
6084 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006085
6086 void VisitExpr(Expr *E) {
6087 if (isa<ObjCMessageExpr>(*E)) return;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006088 if (isRecordType) {
6089 Expr *expr = E;
6090 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6091 ValueDecl *VD = ME->getMemberDecl();
6092 if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
6093 expr = ME->getBase();
6094 }
6095 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
6096 HandleDeclRefExpr(DRE);
6097 return;
6098 }
6099 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006100 Inherited::VisitExpr(E);
6101 }
6102
Richard Trieua04ad1a2011-09-01 21:44:13 +00006103 void VisitMemberExpr(MemberExpr *E) {
Richard Trieuaa5e2562011-09-07 00:58:53 +00006104 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu978dfc02012-03-08 01:15:31 +00006105 ValueDecl *VD = E->getMemberDecl();
6106 if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
Richard Trieua04ad1a2011-09-01 21:44:13 +00006107 if (DeclRefExpr *DRE
6108 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6109 HandleDeclRefExpr(DRE);
6110 return;
6111 }
6112 Inherited::VisitMemberExpr(E);
6113 }
6114
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006115 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00006116 if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
6117 (isRecordType && E->getCastKind() == CK_NoOp)) {
6118 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
6119 if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
6120 SubExpr = ME->getBase()->IgnoreParenImpCasts();
6121 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6122 HandleDeclRefExpr(DRE);
6123 return;
6124 }
6125 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006126 Inherited::VisitImplicitCastExpr(E);
6127 }
6128
Richard Trieua04ad1a2011-09-01 21:44:13 +00006129 void VisitUnaryOperator(UnaryOperator *E) {
6130 // For POD record types, addresses of its own members are well-defined.
6131 if (isRecordType && isPODType) return;
6132 Inherited::VisitUnaryOperator(E);
6133 }
6134
6135 void HandleDeclRefExpr(DeclRefExpr *DRE) {
6136 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006137 if (OrigDecl != ReferenceDecl) return;
6138 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6139 Sema::NotForRedeclaration);
Richard Trieua04ad1a2011-09-01 21:44:13 +00006140 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006141 S.PDiag(diag::warn_uninit_self_reference_in_init)
Richard Trieua04ad1a2011-09-01 21:44:13 +00006142 << Result.getLookupName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006143 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00006144 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006145 }
6146 };
6147}
6148
Richard Trieua04ad1a2011-09-01 21:44:13 +00006149/// CheckSelfReference - Warns if OrigDecl is used in expression E.
6150void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
6151 SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
6152}
6153
Douglas Gregor5fb53972009-01-14 15:45:31 +00006154/// AddInitializerToDecl - Adds the initializer Init to the
6155/// declaration dcl. If DirectInit is true, this is C++ direct
6156/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00006157void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6158 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00006159 // If there is no declaration, there was an error parsing it. Just ignore
6160 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00006161 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00006162 return;
Mike Stump11289f42009-09-09 15:08:12 +00006163
Douglas Gregor0c880302009-03-11 23:00:04 +00006164 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6165 // With declarators parsed the way they are, the parser cannot
6166 // distinguish between a normal initializer and a pure-specifier.
6167 // Thus this grotesque test.
6168 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00006169 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00006170 Context.getCanonicalType(IL->getType()) == Context.IntTy)
6171 CheckPureMethod(Method, Init->getSourceRange());
6172 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00006173 Diag(Method->getLocation(), diag::err_member_function_initialization)
6174 << Method->getDeclName() << Init->getSourceRange();
6175 Method->setInvalidDecl();
6176 }
6177 return;
6178 }
6179
Steve Naroff437b4d82007-09-12 20:13:48 +00006180 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6181 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00006182 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6183 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00006184 RealDecl->setInvalidDecl();
6185 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00006186 }
6187
Sebastian Redla9351792012-02-11 23:51:47 +00006188 // Check for self-references within variable initializers.
6189 // Variables declared within a function/method body are handled
6190 // by a dataflow analysis.
6191 if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6192 CheckSelfReference(RealDecl, Init);
6193
6194 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6195
Richard Smith0cc85782011-12-15 19:20:59 +00006196 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith30482bc2011-02-20 03:19:35 +00006197 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00006198 Expr *DeduceInit = Init;
6199 // Initializer could be a C++ direct-initializer. Deduction only works if it
6200 // contains exactly one expression.
6201 if (CXXDirectInit) {
6202 if (CXXDirectInit->getNumExprs() == 0) {
6203 // It isn't possible to write this directly, but it is possible to
6204 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006205 Diag(CXXDirectInit->getLocStart(),
Sebastian Redla9351792012-02-11 23:51:47 +00006206 diag::err_auto_var_init_no_expression)
6207 << VDecl->getDeclName() << VDecl->getType()
6208 << VDecl->getSourceRange();
6209 RealDecl->setInvalidDecl();
6210 return;
6211 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006212 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Sebastian Redla9351792012-02-11 23:51:47 +00006213 diag::err_auto_var_init_multiple_expressions)
6214 << VDecl->getDeclName() << VDecl->getType()
6215 << VDecl->getSourceRange();
6216 RealDecl->setInvalidDecl();
6217 return;
6218 } else {
6219 DeduceInit = CXXDirectInit->getExpr(0);
6220 }
6221 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006222 TypeSourceInfo *DeducedType = 0;
Sebastian Redla9351792012-02-11 23:51:47 +00006223 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00006224 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00006225 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9647d3c2011-03-17 16:11:59 +00006226 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006227 RealDecl->setInvalidDecl();
6228 return;
6229 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006230 VDecl->setTypeSourceInfo(DeducedType);
6231 VDecl->setType(DeducedType->getType());
Douglas Gregord5c48442012-02-20 20:05:29 +00006232 VDecl->ClearLinkageCache();
6233
John McCall31168b02011-06-15 23:02:42 +00006234 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006235 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00006236 VDecl->setInvalidDecl();
6237
Richard Smith30482bc2011-02-20 03:19:35 +00006238 // If this is a redeclaration, check that the type we just deduced matches
6239 // the previously declared type.
Douglas Gregorec9fd132012-01-14 16:38:05 +00006240 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith30482bc2011-02-20 03:19:35 +00006241 MergeVarDeclTypes(VDecl, Old);
6242 }
Richard Smith0cc85782011-12-15 19:20:59 +00006243
6244 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6245 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6246 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6247 VDecl->setInvalidDecl();
6248 return;
6249 }
6250
Sebastian Redla9351792012-02-11 23:51:47 +00006251 if (!VDecl->getType()->isDependentType()) {
6252 // A definition must end up with a complete type, which means it must be
6253 // complete with the restriction that an array type might be completed by
6254 // the initializer; note that later code assumes this restriction.
6255 QualType BaseDeclType = VDecl->getType();
6256 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6257 BaseDeclType = Array->getElementType();
6258 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6259 diag::err_typecheck_decl_incomplete_type)) {
6260 RealDecl->setInvalidDecl();
6261 return;
6262 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00006263
Sebastian Redla9351792012-02-11 23:51:47 +00006264 // The variable can not have an abstract class type.
6265 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6266 diag::err_abstract_type_in_decl,
6267 AbstractVariableType))
6268 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00006269 }
6270
Sebastian Redl5ca79842010-02-01 20:16:42 +00006271 const VarDecl *Def;
6272 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00006273 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00006274 << VDecl->getDeclName();
6275 Diag(Def->getLocation(), diag::note_previous_definition);
6276 VDecl->setInvalidDecl();
6277 return;
6278 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00006279
Douglas Gregorf0f83692010-08-24 05:27:49 +00006280 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006281 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00006282 // C++ [class.static.data]p4
6283 // If a static data member is of const integral or const
6284 // enumeration type, its declaration in the class definition can
6285 // specify a constant-initializer which shall be an integral
6286 // constant expression (5.19). In that case, the member can appear
6287 // in integral constant expressions. The member shall still be
6288 // defined in a namespace scope if it is used in the program and the
6289 // namespace scope definition shall not contain an initializer.
6290 //
6291 // We already performed a redefinition check above, but for static
6292 // data members we also need to check whether there was an in-class
6293 // declaration with an initializer.
6294 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikie30d15442011-10-19 22:56:21 +00006295 Diag(VDecl->getLocation(), diag::err_redefinition)
6296 << VDecl->getDeclName();
Douglas Gregor71f39c92010-12-16 01:31:22 +00006297 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6298 return;
6299 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00006300
Douglas Gregor71f39c92010-12-16 01:31:22 +00006301 if (VDecl->hasLocalStorage())
6302 getCurFunction()->setHasBranchProtectedScope();
6303
6304 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6305 VDecl->setInvalidDecl();
6306 return;
6307 }
6308 }
John McCalld4e1b762010-08-01 01:24:59 +00006309
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00006310 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6311 // a kernel function cannot be initialized."
6312 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6313 Diag(VDecl->getLocation(), diag::err_local_cant_init);
6314 VDecl->setInvalidDecl();
6315 return;
6316 }
6317
Steve Naroff61091402007-09-12 14:07:44 +00006318 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00006319 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00006320 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00006321
6322 // Top-level message sends default to 'id' when we're in a debugger
6323 // and we are assigning it to a variable of 'id' type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006324 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00006325 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6326 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6327 if (Result.isInvalid()) {
6328 VDecl->setInvalidDecl();
6329 return;
6330 }
6331 Init = Result.take();
6332 }
Richard Smith0cc85782011-12-15 19:20:59 +00006333
6334 // Perform the initialization.
6335 if (!VDecl->isInvalidDecl()) {
6336 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6337 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00006338 = DirectInit ?
6339 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6340 Init->getLocStart(),
6341 Init->getLocEnd())
6342 : InitializationKind::CreateDirectList(
6343 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00006344 : InitializationKind::CreateCopy(VDecl->getLocation(),
6345 Init->getLocStart());
6346
Sebastian Redla9351792012-02-11 23:51:47 +00006347 Expr **Args = &Init;
6348 unsigned NumArgs = 1;
6349 if (CXXDirectInit) {
6350 Args = CXXDirectInit->getExprs();
6351 NumArgs = CXXDirectInit->getNumExprs();
6352 }
6353 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
Richard Smith0cc85782011-12-15 19:20:59 +00006354 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redla9351792012-02-11 23:51:47 +00006355 MultiExprArg(*this, Args,NumArgs),
Richard Smith0cc85782011-12-15 19:20:59 +00006356 &DclT);
6357 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00006358 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00006359 return;
Steve Naroff61091402007-09-12 14:07:44 +00006360 }
Richard Smith0cc85782011-12-15 19:20:59 +00006361
6362 Init = Result.takeAs<Expr>();
6363 }
6364
6365 // If the type changed, it means we had an incomplete type that was
6366 // completed by the initializer. For example:
6367 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00006368 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00006369 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00006370 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00006371
6372 // Check any implicit conversions within the expression.
6373 CheckImplicitConversions(Init, VDecl->getLocation());
6374
6375 if (!VDecl->isInvalidDecl())
6376 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6377
6378 Init = MaybeCreateExprWithCleanups(Init);
6379 // Attach the initializer to the decl.
6380 VDecl->setInit(Init);
6381
6382 if (VDecl->isLocalVarDecl()) {
6383 // C99 6.7.8p4: All the expressions in an initializer for an object that has
6384 // static storage duration shall be constant expressions or string literals.
6385 // C++ does not have this restriction.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006386 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
Richard Smith0cc85782011-12-15 19:20:59 +00006387 VDecl->getStorageClass() == SC_Static)
6388 CheckForConstantInitializer(Init, DclT);
Mike Stump11289f42009-09-09 15:08:12 +00006389 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00006390 VDecl->getLexicalDeclContext()->isRecord()) {
6391 // This is an in-class initialization for a static data member, e.g.,
6392 //
6393 // struct S {
6394 // static const int value = 17;
6395 // };
6396
Douglas Gregor0c880302009-03-11 23:00:04 +00006397 // C++ [class.mem]p4:
6398 // A member-declarator can contain a constant-initializer only
6399 // if it declares a static member (9.4) of const integral or
6400 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00006401 //
Richard Smith0cc85782011-12-15 19:20:59 +00006402 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00006403 // If a non-volatile const static data member is of integral or
6404 // enumeration type, its declaration in the class definition can
6405 // specify a brace-or-equal-initializer in which every initalizer-clause
6406 // that is an assignment-expression is a constant expression. A static
6407 // data member of literal type can be declared in the class definition
6408 // with the constexpr specifier; if so, its declaration shall specify a
6409 // brace-or-equal-initializer in which every initializer-clause that is
6410 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00006411
6412 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00006413 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00006414
Richard Smith2316cd82011-09-29 19:11:37 +00006415 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00006416 // type. We separately check that every constexpr variable is of literal
6417 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00006418 } else if (VDecl->isConstexpr()) {
6419
John McCalldb768922010-09-10 23:21:22 +00006420 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00006421 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00006422 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6423 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00006424 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00006425
6426 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00006427 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00006428 // Check whether the expression is a constant expression.
6429 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006430 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00006431 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00006432 // in-class initializer cannot be volatile.
6433 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6434 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00006435 ; // Nothing to check.
6436 else if (Init->isIntegerConstantExpr(Context, &Loc))
6437 ; // Ok, it's an ICE!
6438 else if (Init->isEvaluatable(Context)) {
6439 // If we can constant fold the initializer through heroics, accept it,
6440 // but report this as a use of an extension for -pedantic.
6441 Diag(Loc, diag::ext_in_class_initializer_non_constant)
6442 << Init->getSourceRange();
6443 } else {
6444 // Otherwise, this is some crazy unknown case. Report the issue at the
6445 // location provided by the isIntegerConstantExpr failed check.
6446 Diag(Loc, diag::err_in_class_initializer_non_constant)
6447 << Init->getSourceRange();
6448 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00006449 }
6450
Richard Smith0cc85782011-12-15 19:20:59 +00006451 // We allow foldable floating-point constants as an extension.
6452 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smith2316cd82011-09-29 19:11:37 +00006453 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006454 << DclT << Init->getSourceRange();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006455 if (getLangOpts().CPlusPlus0x)
Richard Smith7b729cd2011-09-30 00:33:19 +00006456 Diag(VDecl->getLocation(),
6457 diag::note_in_class_initializer_float_type_constexpr)
6458 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
John McCalldb768922010-09-10 23:21:22 +00006459
Richard Smith0cc85782011-12-15 19:20:59 +00006460 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
John McCalldb768922010-09-10 23:21:22 +00006461 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6462 << Init->getSourceRange();
6463 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00006464 }
Richard Smith256336d2011-09-29 23:18:34 +00006465
Richard Smith0cc85782011-12-15 19:20:59 +00006466 // Suggest adding 'constexpr' in C++11 for literal types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006467 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
Richard Smith256336d2011-09-29 23:18:34 +00006468 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006469 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00006470 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6471 VDecl->setConstexpr(true);
6472
Richard Smith2316cd82011-09-29 19:11:37 +00006473 } else {
6474 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006475 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00006476 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00006477 }
Steve Naroff08899ff2008-04-15 22:42:06 +00006478 } else if (VDecl->isFileVarDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00006479 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006480 (!getLangOpts().CPlusPlus ||
Douglas Gregorfceea362010-04-22 14:36:26 +00006481 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00006482 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00006483
Richard Smith0cc85782011-12-15 19:20:59 +00006484 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006485 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00006486 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00006487 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00006488
Sebastian Redla9351792012-02-11 23:51:47 +00006489 // We will represent direct-initialization similarly to copy-initialization:
6490 // int x(1); -as-> int x = 1;
6491 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6492 //
6493 // Clients that want to distinguish between the two forms, can check for
6494 // direct initializer using VarDecl::getInitStyle().
6495 // A major benefit is that clients that don't particularly care about which
6496 // exactly form was it (like the CodeGen) can handle both cases without
6497 // special case code.
6498
6499 // C++ 8.5p11:
6500 // The form of initialization (using parentheses or '=') is generally
6501 // insignificant, but does matter when the entity being initialized has a
6502 // class type.
6503 if (CXXDirectInit) {
6504 assert(DirectInit && "Call-style initializer must be direct init.");
6505 VDecl->setInitStyle(VarDecl::CallInit);
6506 } else if (DirectInit) {
6507 // This must be list-initialization. No other way is direct-initialization.
6508 VDecl->setInitStyle(VarDecl::ListInit);
6509 }
6510
John McCall8b7fd8f12011-01-19 11:48:09 +00006511 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00006512}
6513
John McCalleae5acb2010-03-31 02:13:20 +00006514/// ActOnInitializerError - Given that there was an error parsing an
6515/// initializer for the given declaration, try to return to some form
6516/// of sanity.
John McCall48871652010-08-21 09:40:31 +00006517void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00006518 // Our main concern here is re-establishing invariants like "a
6519 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00006520 if (!D || D->isInvalidDecl()) return;
6521
6522 VarDecl *VD = dyn_cast<VarDecl>(D);
6523 if (!VD) return;
6524
Richard Smith30482bc2011-02-20 03:19:35 +00006525 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00006526 if (ParsingInitForAutoVars.count(D)) {
6527 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00006528 return;
6529 }
6530
John McCalleae5acb2010-03-31 02:13:20 +00006531 QualType Ty = VD->getType();
6532 if (Ty->isDependentType()) return;
6533
6534 // Require a complete type.
6535 if (RequireCompleteType(VD->getLocation(),
6536 Context.getBaseElementType(Ty),
6537 diag::err_typecheck_decl_incomplete_type)) {
6538 VD->setInvalidDecl();
6539 return;
6540 }
6541
6542 // Require an abstract type.
6543 if (RequireNonAbstractType(VD->getLocation(), Ty,
6544 diag::err_abstract_type_in_decl,
6545 AbstractVariableType)) {
6546 VD->setInvalidDecl();
6547 return;
6548 }
6549
6550 // Don't bother complaining about constructors or destructors,
6551 // though.
6552}
6553
John McCall48871652010-08-21 09:40:31 +00006554void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00006555 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00006556 // If there is no declaration, there was an error parsing it. Just ignore it.
6557 if (RealDecl == 0)
6558 return;
6559
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006560 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6561 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00006562
Richard Smithf0215fe2011-12-25 21:17:58 +00006563 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00006564 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00006565 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6566 << Var->getDeclName() << Type;
6567 Var->setInvalidDecl();
6568 return;
6569 }
Mike Stump11289f42009-09-09 15:08:12 +00006570
Richard Smithf0215fe2011-12-25 21:17:58 +00006571 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00006572 // the constexpr specifier; if so, its declaration shall specify
6573 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00006574 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6575 // the definition of a variable [...] or the declaration of a static data
6576 // member.
6577 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6578 if (Var->isStaticDataMember())
6579 Diag(Var->getLocation(),
6580 diag::err_constexpr_static_mem_var_requires_init)
6581 << Var->getDeclName();
6582 else
6583 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00006584 Var->setInvalidDecl();
6585 return;
6586 }
6587
Douglas Gregore6565622010-02-09 07:26:29 +00006588 switch (Var->isThisDeclarationADefinition()) {
6589 case VarDecl::Definition:
6590 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6591 break;
6592
6593 // We have an out-of-line definition of a static data member
6594 // that has an in-class initializer, so we type-check this like
6595 // a declaration.
6596 //
6597 // Fall through
6598
6599 case VarDecl::DeclarationOnly:
6600 // It's only a declaration.
6601
6602 // Block scope. C99 6.7p7: If an identifier for an object is
6603 // declared with no linkage (C99 6.2.2p6), the type for the
6604 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00006605 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00006606 !Var->getLinkage() && !Var->isInvalidDecl() &&
6607 RequireCompleteType(Var->getLocation(), Type,
6608 diag::err_typecheck_decl_incomplete_type))
6609 Var->setInvalidDecl();
6610
6611 // Make sure that the type is not abstract.
6612 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6613 RequireNonAbstractType(Var->getLocation(), Type,
6614 diag::err_abstract_type_in_decl,
6615 AbstractVariableType))
6616 Var->setInvalidDecl();
6617 return;
6618
6619 case VarDecl::TentativeDefinition:
6620 // File scope. C99 6.9.2p2: A declaration of an identifier for an
6621 // object that has file scope without an initializer, and without a
6622 // storage-class specifier or with the storage-class specifier "static",
6623 // constitutes a tentative definition. Note: A tentative definition with
6624 // external linkage is valid (C99 6.2.2p5).
6625 if (!Var->isInvalidDecl()) {
6626 if (const IncompleteArrayType *ArrayT
6627 = Context.getAsIncompleteArrayType(Type)) {
6628 if (RequireCompleteType(Var->getLocation(),
6629 ArrayT->getElementType(),
6630 diag::err_illegal_decl_array_incomplete_type))
6631 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00006632 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00006633 // C99 6.9.2p3: If the declaration of an identifier for an object is
6634 // a tentative definition and has internal linkage (C99 6.2.2p3), the
6635 // declared type shall not be an incomplete type.
6636 // NOTE: code such as the following
6637 // static struct s;
6638 // struct s { int a; };
6639 // is accepted by gcc. Hence here we issue a warning instead of
6640 // an error and we do not invalidate the static declaration.
6641 // NOTE: to avoid multiple warnings, only check the first declaration.
Douglas Gregorec9fd132012-01-14 16:38:05 +00006642 if (Var->getPreviousDecl() == 0)
Douglas Gregore6565622010-02-09 07:26:29 +00006643 RequireCompleteType(Var->getLocation(), Type,
6644 diag::ext_typecheck_decl_incomplete_type);
6645 }
6646 }
6647
6648 // Record the tentative definition; we're done.
6649 if (!Var->isInvalidDecl())
6650 TentativeDefinitions.push_back(Var);
6651 return;
6652 }
6653
6654 // Provide a specific diagnostic for uninitialized variable
6655 // definitions with incomplete array type.
6656 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00006657 Diag(Var->getLocation(),
6658 diag::err_typecheck_incomplete_array_needs_initializer);
6659 Var->setInvalidDecl();
6660 return;
6661 }
6662
John McCalla755f0f2010-08-01 01:25:24 +00006663 // Provide a specific diagnostic for uninitialized variable
6664 // definitions with reference type.
6665 if (Type->isReferenceType()) {
6666 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6667 << Var->getDeclName()
6668 << SourceRange(Var->getLocation(), Var->getLocation());
6669 Var->setInvalidDecl();
6670 return;
6671 }
Douglas Gregore6565622010-02-09 07:26:29 +00006672
6673 // Do not attempt to type-check the default initializer for a
6674 // variable with dependent type.
6675 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00006676 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006677
Douglas Gregore6565622010-02-09 07:26:29 +00006678 if (Var->isInvalidDecl())
6679 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00006680
Douglas Gregore6565622010-02-09 07:26:29 +00006681 if (RequireCompleteType(Var->getLocation(),
6682 Context.getBaseElementType(Type),
6683 diag::err_typecheck_decl_incomplete_type)) {
6684 Var->setInvalidDecl();
6685 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006686 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006687
Douglas Gregore6565622010-02-09 07:26:29 +00006688 // The variable can not have an abstract class type.
6689 if (RequireNonAbstractType(Var->getLocation(), Type,
6690 diag::err_abstract_type_in_decl,
6691 AbstractVariableType)) {
6692 Var->setInvalidDecl();
6693 return;
6694 }
6695
Douglas Gregor9574af62011-05-21 17:52:48 +00006696 // Check for jumps past the implicit initializer. C++0x
6697 // clarifies that this applies to a "variable with automatic
6698 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00006699 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00006700 // A program that jumps from a point where a variable with automatic
6701 // storage duration is not in scope to a point where it is in scope is
6702 // ill-formed unless the variable has scalar type, class type with a
6703 // trivial default constructor and a trivial destructor, a cv-qualified
6704 // version of one of these types, or an array of one of the preceding
6705 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006706 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00006707 if (const RecordType *Record
6708 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00006709 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00006710 // Mark the function for further checking even if the looser rules of
6711 // C++11 do not require such checks, so that we can diagnose
6712 // incompatibilities with C++98.
6713 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00006714 getCurFunction()->setHasBranchProtectedScope();
6715 }
Douglas Gregore6565622010-02-09 07:26:29 +00006716 }
Douglas Gregor9574af62011-05-21 17:52:48 +00006717
6718 // C++03 [dcl.init]p9:
6719 // If no initializer is specified for an object, and the
6720 // object is of (possibly cv-qualified) non-POD class type (or
6721 // array thereof), the object shall be default-initialized; if
6722 // the object is of const-qualified type, the underlying class
6723 // type shall have a user-declared default
6724 // constructor. Otherwise, if no initializer is specified for
6725 // a non- static object, the object and its subobjects, if
6726 // any, have an indeterminate initial value); if the object
6727 // or any of its subobjects are of const-qualified type, the
6728 // program is ill-formed.
6729 // C++0x [dcl.init]p11:
6730 // If no initializer is specified for an object, the object is
6731 // default-initialized; [...].
6732 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6733 InitializationKind Kind
6734 = InitializationKind::CreateDefault(Var->getLocation());
6735
6736 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6737 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6738 MultiExprArg(*this, 0, 0));
6739 if (Init.isInvalid())
6740 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00006741 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00006742 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00006743 // This is important for template substitution.
6744 Var->setInitStyle(VarDecl::CallInit);
6745 }
Douglas Gregor589973b2010-03-08 02:45:10 +00006746
John McCall8b7fd8f12011-01-19 11:48:09 +00006747 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006748 }
6749}
6750
Richard Smith02e85f32011-04-14 22:09:26 +00006751void Sema::ActOnCXXForRangeDecl(Decl *D) {
6752 VarDecl *VD = dyn_cast<VarDecl>(D);
6753 if (!VD) {
6754 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6755 D->setInvalidDecl();
6756 return;
6757 }
6758
6759 VD->setCXXForRangeDecl(true);
6760
6761 // for-range-declaration cannot be given a storage class specifier.
6762 int Error = -1;
6763 switch (VD->getStorageClassAsWritten()) {
6764 case SC_None:
6765 break;
6766 case SC_Extern:
6767 Error = 0;
6768 break;
6769 case SC_Static:
6770 Error = 1;
6771 break;
6772 case SC_PrivateExtern:
6773 Error = 2;
6774 break;
6775 case SC_Auto:
6776 Error = 3;
6777 break;
6778 case SC_Register:
6779 Error = 4;
6780 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00006781 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00006782 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00006783 }
Richard Smith2316cd82011-09-29 19:11:37 +00006784 if (VD->isConstexpr())
6785 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00006786 if (Error != -1) {
6787 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6788 << VD->getDeclName() << Error;
6789 D->setInvalidDecl();
6790 }
6791}
6792
John McCall8b7fd8f12011-01-19 11:48:09 +00006793void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6794 if (var->isInvalidDecl()) return;
6795
John McCall31168b02011-06-15 23:02:42 +00006796 // In ARC, don't allow jumps past the implicit initialization of a
6797 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006798 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006799 var->hasLocalStorage()) {
6800 switch (var->getType().getObjCLifetime()) {
6801 case Qualifiers::OCL_None:
6802 case Qualifiers::OCL_ExplicitNone:
6803 case Qualifiers::OCL_Autoreleasing:
6804 break;
6805
6806 case Qualifiers::OCL_Weak:
6807 case Qualifiers::OCL_Strong:
6808 getCurFunction()->setHasBranchProtectedScope();
6809 break;
6810 }
6811 }
6812
John McCall8b7fd8f12011-01-19 11:48:09 +00006813 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006814 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00006815
6816 QualType baseType = Context.getBaseElementType(var->getType());
6817 if (baseType->isDependentType()) return;
6818
6819 // __block variables might require us to capture a copy-initializer.
6820 if (var->hasAttr<BlocksAttr>()) {
6821 // It's currently invalid to ever have a __block variable with an
6822 // array type; should we diagnose that here?
6823
6824 // Regardless, we don't want to ignore array nesting when
6825 // constructing this copy.
6826 QualType type = var->getType();
6827
6828 if (type->isStructureOrClassType()) {
6829 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00006830 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
John McCall8b7fd8f12011-01-19 11:48:09 +00006831 ExprResult result =
6832 PerformCopyInitialization(
6833 InitializedEntity::InitializeBlock(poi, type, false),
6834 poi, Owned(varRef));
6835 if (!result.isInvalid()) {
6836 result = MaybeCreateExprWithCleanups(result);
6837 Expr *init = result.takeAs<Expr>();
6838 Context.setBlockVarCopyInits(var, init);
6839 }
6840 }
6841 }
6842
Richard Smitheda3c842011-11-07 22:16:17 +00006843 Expr *Init = var->getInit();
6844 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6845
Richard Smithd0b4dd62011-12-19 06:19:21 +00006846 if (!var->getDeclContext()->isDependentContext() && Init) {
6847 if (IsGlobal && !var->isConstexpr() &&
6848 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6849 var->getLocation())
6850 != DiagnosticsEngine::Ignored &&
6851 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
Richard Smitheda3c842011-11-07 22:16:17 +00006852 Diag(var->getLocation(), diag::warn_global_constructor)
6853 << Init->getSourceRange();
Richard Smithd0b4dd62011-12-19 06:19:21 +00006854
Richard Smithd0b4dd62011-12-19 06:19:21 +00006855 if (var->isConstexpr()) {
6856 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6857 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6858 SourceLocation DiagLoc = var->getLocation();
6859 // If the note doesn't add any useful information other than a source
6860 // location, fold it into the primary diagnostic.
6861 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6862 diag::note_invalid_subexpr_in_const_expr) {
6863 DiagLoc = Notes[0].first;
6864 Notes.clear();
6865 }
6866 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6867 << var << Init->getSourceRange();
6868 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6869 Diag(Notes[I].first, Notes[I].second);
6870 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00006871 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00006872 // Check whether the initializer of a const variable of integral or
6873 // enumeration type is an ICE now, since we can't tell whether it was
6874 // initialized by a constant expression if we check later.
6875 var->checkInitIsICE();
6876 }
Richard Smitheda3c842011-11-07 22:16:17 +00006877 }
John McCall8b7fd8f12011-01-19 11:48:09 +00006878
6879 // Require the destructor.
6880 if (const RecordType *recordType = baseType->getAs<RecordType>())
6881 FinalizeVarWithDestructor(var, recordType);
6882}
6883
Richard Smithb2bc2e62011-02-21 20:05:19 +00006884/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6885/// any semantic actions necessary after any initializer has been attached.
6886void
6887Sema::FinalizeDeclaration(Decl *ThisDecl) {
6888 // Note that we are no longer parsing the initializer for this declaration.
6889 ParsingInitForAutoVars.erase(ThisDecl);
6890}
6891
John McCallba7bf592010-08-24 05:47:05 +00006892Sema::DeclGroupPtrTy
6893Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6894 Decl **Group, unsigned NumDecls) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006895 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00006896
6897 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00006898 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00006899
Richard Smith2abf6762011-02-23 00:37:57 +00006900 for (unsigned i = 0; i != NumDecls; ++i)
6901 if (Decl *D = Group[i])
6902 Decls.push_back(D);
6903
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006904 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00006905 DS.getTypeSpecType() == DeclSpec::TST_auto);
6906}
6907
6908/// BuildDeclaratorGroup - convert a list of declarations into a declaration
6909/// group, performing any necessary semantic checking.
6910Sema::DeclGroupPtrTy
6911Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6912 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00006913 // C++0x [dcl.spec.auto]p7:
6914 // If the type deduced for the template parameter U is not the same in each
6915 // deduction, the program is ill-formed.
6916 // FIXME: When initializer-list support is added, a distinction is needed
6917 // between the deduced type U and the deduced type which 'auto' stands for.
6918 // auto a = 0, b = { 1, 2, 3 };
6919 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00006920 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00006921 QualType Deduced;
6922 CanQualType DeducedCanon;
6923 VarDecl *DeducedDecl = 0;
6924 for (unsigned i = 0; i != NumDecls; ++i) {
6925 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6926 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00006927 // Don't reissue diagnostics when instantiating a template.
6928 if (AT && D->isInvalidDecl())
6929 break;
Richard Smith30482bc2011-02-20 03:19:35 +00006930 if (AT && AT->isDeduced()) {
6931 QualType U = AT->getDeducedType();
6932 CanQualType UCanon = Context.getCanonicalType(U);
6933 if (Deduced.isNull()) {
6934 Deduced = U;
6935 DeducedCanon = UCanon;
6936 DeducedDecl = D;
6937 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00006938 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6939 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00006940 << Deduced << DeducedDecl->getDeclName()
6941 << U << D->getDeclName()
6942 << DeducedDecl->getInit()->getSourceRange()
6943 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00006944 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00006945 break;
6946 }
6947 }
6948 }
6949 }
6950 }
6951
Richard Smith2abf6762011-02-23 00:37:57 +00006952 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00006953}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00006954
Chris Lattner5bbb3c82009-03-29 16:50:03 +00006955
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006956/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6957/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00006958Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00006959 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00006960
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006961 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Peter Collingbourne99eddc32011-10-21 11:55:09 +00006962 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00006963 VarDecl::StorageClass StorageClass = SC_None;
6964 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00006965 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00006966 StorageClass = SC_Register;
6967 StorageClassAsWritten = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006968 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00006969 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6970 StorageClass = SC_Auto;
6971 StorageClassAsWritten = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00006972 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006973 Diag(DS.getStorageClassSpecLoc(),
6974 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00006975 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006976 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006977
6978 if (D.getDeclSpec().isThreadSpecified())
6979 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00006980 if (D.getDeclSpec().isConstexprSpecified())
6981 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6982 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006983
Eli Friedman574c7452009-04-07 19:37:57 +00006984 DiagnoseFunctionSpecifiers(D);
6985
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00006986 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00006987 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006988
David Blaikiebbafb8a2012-03-11 07:00:24 +00006989 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00006990 // Check that there are no default arguments inside the type of this
6991 // parameter.
6992 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00006993
6994 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6995 if (D.getCXXScopeSpec().isSet()) {
6996 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6997 << D.getCXXScopeSpec().getRange();
6998 D.getCXXScopeSpec().clear();
6999 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00007000 }
7001
Alexis Hunta56cbcc2010-11-03 01:07:06 +00007002 // Ensure we have a valid name
7003 IdentifierInfo *II = 0;
7004 if (D.hasName()) {
7005 II = D.getIdentifier();
7006 if (!II) {
7007 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7008 << GetNameForDeclarator(D).getName().getAsString();
7009 D.setInvalidType(true);
7010 }
7011 }
7012
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00007013 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00007014 if (II) {
John McCall84f02672010-03-18 06:42:38 +00007015 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7016 ForRedeclaration);
7017 LookupName(R, S);
7018 if (R.isSingleResult()) {
7019 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00007020 if (PrevDecl->isTemplateParameter()) {
7021 // Maybe we will complain about the shadowed template parameter.
7022 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7023 // Just pretend that we didn't see the previous declaration.
7024 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00007025 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00007026 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00007027 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007028
Chris Lattnerd9773512009-01-21 02:38:50 +00007029 // Recover by removing the name
7030 II = 0;
7031 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007032 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00007033 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007034 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00007035 }
Steve Naroff773df5c2007-08-07 22:44:21 +00007036
John McCallf7b2fb52010-01-22 00:28:27 +00007037 // Temporarily put parameter variables in the translation unit, not
7038 // the enclosing context. This prevents them from accidentally
7039 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00007040 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007041 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00007042 D.getIdentifierLoc(), II,
7043 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007044 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00007045
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007046 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00007047 New->setInvalidDecl();
7048
7049 assert(S->isFunctionPrototypeScope());
7050 assert(S->getFunctionPrototypeDepth() >= 1);
7051 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7052 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00007053
Douglas Gregor91f84212008-12-11 16:49:14 +00007054 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00007055 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00007056 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00007057 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00007058
Douglas Gregor758a8692009-06-17 21:51:59 +00007059 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00007060
Douglas Gregor41866812011-09-12 18:37:38 +00007061 if (D.getDeclSpec().isModulePrivateSpecified())
7062 Diag(New->getLocation(), diag::err_module_private_local)
7063 << 1 << New->getDeclName()
7064 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7065 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7066
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007067 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00007068 Diag(New->getLocation(), diag::err_block_on_nonlocal);
7069 }
John McCall48871652010-08-21 09:40:31 +00007070 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00007071}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00007072
John McCalla3ccba02010-06-04 11:21:44 +00007073/// \brief Synthesizes a variable for a parameter arising from a
7074/// typedef.
7075ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7076 SourceLocation Loc,
7077 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007078 /* FIXME: setting StartLoc == Loc.
7079 Would it be worth to modify callers so as to provide proper source
7080 location for the unnamed parameters, embedding the parameter's type? */
7081 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00007082 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007083 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00007084 Param->setImplicit();
7085 return Param;
7086}
7087
John McCallc5990642010-08-24 09:05:15 +00007088void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7089 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00007090 // Don't diagnose unused-parameter errors in template instantiations; we
7091 // will already have done so in the template itself.
7092 if (!ActiveTemplateInstantiations.empty())
7093 return;
7094
7095 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00007096 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00007097 !(*Param)->hasAttr<UnusedAttr>()) {
7098 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7099 << (*Param)->getDeclName();
7100 }
7101 }
7102}
7103
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007104void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7105 ParmVarDecl * const *ParamEnd,
7106 QualType ReturnTy,
7107 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007108 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007109 return;
7110
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007111 // Warn if the return value is pass-by-value and larger than the specified
7112 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00007113 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007114 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007115 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007116 Diag(D->getLocation(), diag::warn_return_value_size)
7117 << D->getDeclName() << Size;
7118 }
7119
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007120 // Warn if any parameter is pass-by-value and larger than the specified
7121 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007122 for (; Param != ParamEnd; ++Param) {
7123 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00007124 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007125 continue;
7126 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007127 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007128 Diag((*Param)->getLocation(), diag::warn_parameter_size)
7129 << (*Param)->getDeclName() << Size;
7130 }
7131}
7132
Abramo Bagnaradff19302011-03-08 08:55:46 +00007133ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7134 SourceLocation NameLoc, IdentifierInfo *Name,
7135 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007136 VarDecl::StorageClass StorageClass,
7137 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00007138 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007139 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00007140 T.getObjCLifetime() == Qualifiers::OCL_None &&
7141 T->isObjCLifetimeType()) {
7142
7143 Qualifiers::ObjCLifetime lifetime;
7144
7145 // Special cases for arrays:
7146 // - if it's const, use __unsafe_unretained
7147 // - otherwise, it's an error
7148 if (T->isArrayType()) {
7149 if (!T.isConstQualified()) {
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00007150 DelayedDiagnostics.add(
7151 sema::DelayedDiagnostic::makeForbiddenType(
7152 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
John McCall31168b02011-06-15 23:02:42 +00007153 }
7154 lifetime = Qualifiers::OCL_ExplicitNone;
7155 } else {
7156 lifetime = T->getObjCARCImplicitLifetime();
7157 }
7158 T = Context.getLifetimeQualifiedType(T, lifetime);
7159 }
7160
Abramo Bagnaradff19302011-03-08 08:55:46 +00007161 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00007162 Context.getAdjustedParameterType(T),
7163 TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007164 StorageClass, StorageClassAsWritten,
7165 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00007166
7167 // Parameters can not be abstract class types.
7168 // For record types, this is done by the AbstractClassUsageDiagnoser once
7169 // the class has been completely parsed.
7170 if (!CurContext->isRecord() &&
7171 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7172 AbstractParamType))
7173 New->setInvalidDecl();
7174
7175 // Parameter declarators cannot be interface types. All ObjC objects are
7176 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00007177 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00007178 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00007179 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7180 << FixItHint::CreateInsertion(NameLoc, "*");
7181 T = Context.getObjCObjectPointerType(T);
7182 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00007183 }
7184
7185 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7186 // duration shall not be qualified by an address-space qualifier."
7187 // Since all parameters have automatic store duration, they can not have
7188 // an address space.
7189 if (T.getAddressSpace() != 0) {
7190 Diag(NameLoc, diag::err_arg_with_address_space);
7191 New->setInvalidDecl();
7192 }
7193
7194 return New;
7195}
7196
Douglas Gregor170512f2009-04-01 23:51:29 +00007197void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7198 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007199 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007200
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007201 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7202 // for a K&R function.
7203 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00007204 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7205 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007206 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007207 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00007208 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00007209 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00007210 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007211 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00007212 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00007213 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00007214
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007215 // Implicitly declare the argument as type 'int' for lack of a better
7216 // type.
John McCall084e83d2011-03-24 11:26:52 +00007217 AttributeFactory attrs;
7218 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007219 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00007220 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00007221 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00007222 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007223 Declarator ParamD(DS, Declarator::KNRTypeListContext);
7224 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00007225 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007226 }
7227 }
Mike Stump11289f42009-09-09 15:08:12 +00007228 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00007229}
7230
Richard Smith79a52e52012-04-17 22:30:01 +00007231Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00007232 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007233 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00007234 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00007235
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007236 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00007237 Decl *DP = HandleDeclarator(ParentScope, D,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007238 MultiTemplateParamsArg(*this));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00007239 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007240}
7241
Anders Carlsson31c7e882009-12-09 03:30:09 +00007242static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7243 // Don't warn about invalid declarations.
7244 if (FD->isInvalidDecl())
7245 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007246
Anders Carlsson31c7e882009-12-09 03:30:09 +00007247 // Or declarations that aren't global.
7248 if (!FD->isGlobal())
7249 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007250
Anders Carlsson31c7e882009-12-09 03:30:09 +00007251 // Don't warn about C++ member functions.
7252 if (isa<CXXMethodDecl>(FD))
7253 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007254
Anders Carlsson31c7e882009-12-09 03:30:09 +00007255 // Don't warn about 'main'.
7256 if (FD->isMain())
7257 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007258
Anders Carlsson31c7e882009-12-09 03:30:09 +00007259 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00007260 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00007261 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007262
7263 // Don't warn about function templates.
7264 if (FD->getDescribedFunctionTemplate())
7265 return false;
7266
7267 // Don't warn about function template specializations.
7268 if (FD->isFunctionTemplateSpecialization())
7269 return false;
7270
Anders Carlsson31c7e882009-12-09 03:30:09 +00007271 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00007272 for (const FunctionDecl *Prev = FD->getPreviousDecl();
7273 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00007274 // Ignore any declarations that occur in function or method
7275 // scope, because they aren't visible from the header.
7276 if (Prev->getDeclContext()->isFunctionOrMethod())
7277 continue;
7278
7279 MissingPrototype = !Prev->getType()->isFunctionProtoType();
7280 break;
7281 }
7282
7283 return MissingPrototype;
7284}
7285
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007286void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7287 // Don't complain if we're in GNU89 mode and the previous definition
7288 // was an extern inline function.
7289 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007290 if (FD->isDefined(Definition) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007291 !canRedefineFunction(Definition, getLangOpts())) {
7292 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007293 Definition->getStorageClass() == SC_Extern)
7294 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007295 << FD->getDeclName() << getLangOpts().CPlusPlus;
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007296 else
7297 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7298 Diag(Definition->getLocation(), diag::note_previous_definition);
7299 }
7300}
7301
John McCall48871652010-08-21 09:40:31 +00007302Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00007303 // Clear the last template instantiation error context.
7304 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7305
Douglas Gregor17a7c122009-06-24 00:54:41 +00007306 if (!D)
7307 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007308 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00007309
John McCall48871652010-08-21 09:40:31 +00007310 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007311 FD = FunTmpl->getTemplatedDecl();
7312 else
John McCall48871652010-08-21 09:40:31 +00007313 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007314
Douglas Gregor9a28e842010-03-01 23:15:13 +00007315 // Enter a new function scope
7316 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00007317
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007318 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007319 if (!FD->isLateTemplateParsed())
7320 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007321
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007322 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00007323 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00007324 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007325 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00007326 FD->setInvalidDecl();
7327 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007328 }
7329
Eli Friedman9ad72442009-03-04 07:30:59 +00007330 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00007331 // (C99 6.9.1p3, C++ [dcl.fct]p6).
7332 QualType ResultType = FD->getResultType();
7333 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00007334 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00007335 RequireCompleteType(FD->getLocation(), ResultType,
7336 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00007337 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00007338
Douglas Gregorf1b876d2009-03-31 16:35:03 +00007339 // GNU warning -Wmissing-prototypes:
7340 // Warn if a global function is defined without a previous
7341 // prototype declaration. This warning is issued even if the
7342 // definition itself provides a prototype. The aim is to detect
7343 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00007344 if (ShouldWarnAboutMissingPrototype(FD))
7345 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00007346
Douglas Gregor67da0d92009-05-15 17:59:04 +00007347 if (FnBodyScope)
7348 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007349
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007350 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00007351 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7352 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007353
7354 // Introduce our parameters into the function scope
7355 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7356 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00007357 Param->setOwningFunction(FD);
7358
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007359 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00007360 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00007361 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00007362
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00007363 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00007364 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00007365 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007366
James Molloy6f8780b2012-02-29 10:24:19 +00007367 // If we had any tags defined in the function prototype,
7368 // introduce them into the function scope.
7369 if (FnBodyScope) {
7370 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7371 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7372 NamedDecl *D = *I;
7373
7374 // Some of these decls (like enums) may have been pinned to the translation unit
7375 // for lack of a real context earlier. If so, remove from the translation unit
7376 // and reattach to the current context.
7377 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7378 // Is the decl actually in the context?
7379 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7380 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7381 if (*DI == D) {
7382 Context.getTranslationUnitDecl()->removeDecl(D);
7383 break;
7384 }
7385 }
7386 // Either way, reassign the lexical decl context to our FunctionDecl.
7387 D->setLexicalDeclContext(CurContext);
7388 }
7389
7390 // If the decl has a non-null name, make accessible in the current scope.
7391 if (!D->getName().empty())
7392 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7393
7394 // Similarly, dive into enums and fish their constants out, making them
7395 // accessible in this scope.
7396 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7397 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7398 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie2d7c57e2012-04-30 02:36:29 +00007399 PushOnScopeChains(&*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00007400 }
7401 }
7402 }
7403
Richard Smith79a52e52012-04-17 22:30:01 +00007404 // Ensure that the function's exception specification is instantiated.
7405 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7406 ResolveExceptionSpec(D->getLocation(), FPT);
7407
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007408 // Checking attributes of current function definition
7409 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007410 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7411 if (DA && (!FD->getAttr<DLLExportAttr>())) {
7412 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00007413 // Microsoft accepts dllimport for functions defined within class scope.
7414 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00007415 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007416 Diag(FD->getLocation(),
7417 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7418 << "dllimport";
7419 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00007420 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00007421 }
7422
7423 // Visual C++ appears to not think this is an issue, so only issue
7424 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00007425 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007426 // If a symbol previously declared dllimport is later defined, the
7427 // attribute is ignored in subsequent references, and a warning is
7428 // emitted.
7429 Diag(FD->getLocation(),
7430 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00007431 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007432 }
7433 }
John McCall48871652010-08-21 09:40:31 +00007434 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00007435}
7436
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007437/// \brief Given the set of return statements within a function body,
7438/// compute the variables that are subject to the named return value
7439/// optimization.
7440///
7441/// Each of the variables that is subject to the named return value
7442/// optimization will be marked as NRVO variables in the AST, and any
7443/// return statement that has a marked NRVO variable as its NRVO candidate can
7444/// use the named return value optimization.
7445///
7446/// This function applies a very simplistic algorithm for NRVO: if every return
7447/// statement in the function has the same NRVO candidate, that candidate is
7448/// the NRVO variable.
7449///
7450/// FIXME: Employ a smarter algorithm that accounts for multiple return
7451/// statements and the lifetimes of the NRVO candidates. We should be able to
7452/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00007453void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00007454 ReturnStmt **Returns = Scope->Returns.data();
7455
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007456 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00007457 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007458 if (!Returns[I]->getNRVOCandidate())
7459 return;
7460
7461 if (!NRVOCandidate)
7462 NRVOCandidate = Returns[I]->getNRVOCandidate();
7463 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7464 return;
7465 }
7466
7467 if (NRVOCandidate)
7468 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7469}
7470
John McCallfaf5fb42010-08-26 23:41:50 +00007471Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00007472 return ActOnFinishFunctionBody(D, move(BodyArg), false);
7473}
7474
John McCallb268a282010-08-23 23:25:46 +00007475Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7476 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007477 FunctionDecl *FD = 0;
7478 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7479 if (FunTmpl)
7480 FD = FunTmpl->getTemplatedDecl();
7481 else
7482 FD = dyn_cast_or_null<FunctionDecl>(dcl);
7483
Ted Kremenek0b405322010-03-23 00:13:23 +00007484 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00007485 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00007486
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007487 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00007488 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00007489
7490 // If the function implicitly returns zero (like 'main') or is naked,
7491 // don't complain about missing return statements.
7492 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00007493 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00007494
Francois Pichet3abc9b82011-05-11 02:14:46 +00007495 // MSVC permits the use of pure specifier (=0) on function definition,
7496 // defined at class scope, warn about this non standard construct.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007497 if (getLangOpts().MicrosoftExt && FD->isPure())
Francois Pichet3abc9b82011-05-11 02:14:46 +00007498 Diag(FD->getLocation(), diag::warn_pure_function_definition);
7499
Douglas Gregor88d292c2010-05-13 16:44:06 +00007500 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007501 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007502 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7503 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007504
7505 // If this is a constructor, we need a vtable.
7506 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7507 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007508
Douglas Gregor49695f02011-09-06 20:46:03 +00007509 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00007510 }
7511
Douglas Gregor21f46922012-02-08 20:17:14 +00007512 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7513 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00007514 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00007515 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00007516 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00007517 if (Body)
7518 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007519 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007520 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007521 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7522 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00007523
7524 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00007525 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007526 }
Nico Weber715abaf2011-08-22 17:25:57 +00007527 if (ObjCShouldCallSuperDealloc) {
7528 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7529 ObjCShouldCallSuperDealloc = false;
7530 }
Nico Weber1fb82662011-08-28 22:35:17 +00007531 if (ObjCShouldCallSuperFinalize) {
7532 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7533 ObjCShouldCallSuperFinalize = false;
7534 }
Ted Kremenek5a201952009-02-07 01:47:29 +00007535 } else {
John McCall48871652010-08-21 09:40:31 +00007536 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00007537 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00007538
Nico Weber715abaf2011-08-22 17:25:57 +00007539 assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7540 "ObjC methods, which should have been handled in the block above.");
Nico Weber1fb82662011-08-28 22:35:17 +00007541 assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7542 "ObjC methods, which should have been handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00007543
Chris Lattnere2473062007-05-28 06:28:18 +00007544 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00007545 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00007546 // C++ constructors that have function-try-blocks can't have return
7547 // statements in the handlers of that block. (C++ [except.handle]p14)
7548 // Verify this.
7549 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7550 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7551
Richard Smithdef8bdb2011-08-12 18:44:32 +00007552 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00007553 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00007554 !dcl->isInvalidDecl() &&
John McCall31168b02011-06-15 23:02:42 +00007555 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00007556 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00007557
John McCalldeb646e2010-08-04 01:04:25 +00007558 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7559 if (!Destructor->getParent()->isDependentType())
7560 CheckDestructor(Destructor);
7561
John McCalla6309952010-03-16 21:39:52 +00007562 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7563 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00007564 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00007565
7566 // If any errors have occurred, clear out any temporaries that may have
7567 // been leftover. This ensures that these temporaries won't be picked up for
7568 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00007569 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00007570 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00007571 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00007572 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00007573 // Since the body is valid, issue any analysis-based warnings that are
7574 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00007575 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00007576 }
7577
Richard Smith3607ffe2012-02-13 03:54:03 +00007578 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7579 (!CheckConstexprFunctionDecl(FD) ||
7580 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00007581 FD->setInvalidDecl();
7582
John McCall28fc7092011-11-10 05:35:25 +00007583 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00007584 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00007585 assert(MaybeODRUseExprs.empty() &&
7586 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00007587 }
7588
John McCalle99d5f32010-03-25 22:08:03 +00007589 if (!IsInstantiation)
7590 PopDeclContext();
7591
Eli Friedman71c80552012-01-05 03:35:19 +00007592 PopFunctionScopeInfo(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00007593
Douglas Gregora7e3ea32009-11-15 07:07:58 +00007594 // If any errors have occurred, clear out any temporaries that may have
7595 // been leftover. This ensures that these temporaries won't be picked up for
7596 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00007597 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00007598 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00007599 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00007600
John McCall48871652010-08-21 09:40:31 +00007601 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00007602}
7603
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00007604
7605/// When we finish delayed parsing of an attribute, we must attach it to the
7606/// relevant Decl.
7607void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7608 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00007609 // Always attach attributes to the underlying decl.
7610 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7611 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00007612 ProcessDeclAttributeList(S, D, Attrs.getList());
7613
7614 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
7615 if (Method->isStatic())
7616 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00007617}
7618
7619
Chris Lattnerac18be92006-11-20 06:49:47 +00007620/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7621/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00007622NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00007623 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00007624 // Before we produce a declaration for an implicitly defined
7625 // function, see whether there was a locally-scoped declaration of
7626 // this name as a function or variable. If so, use that
7627 // (non-visible) declaration, and complain about it.
7628 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00007629 = findLocallyScopedExternalDecl(&II);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00007630 if (Pos != LocallyScopedExternalDecls.end()) {
7631 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7632 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7633 return Pos->second;
7634 }
7635
Chris Lattner00e26072008-05-05 21:18:06 +00007636 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00007637 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00007638 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00007639 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007640 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00007641 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00007642 else
Hans Wennborg70a13242011-12-08 15:56:07 +00007643 diag_id = diag::warn_implicit_function_decl;
7644 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00007645
Hans Wennborg70a13242011-12-08 15:56:07 +00007646 // Because typo correction is expensive, only do it if the implicit
7647 // function declaration is going to be treated as an error.
7648 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7649 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007650 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00007651 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00007652 LookupOrdinaryName, S, 0, Validator))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007653 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7654 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007655 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
Hans Wennborg70a13242011-12-08 15:56:07 +00007656
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007657 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7658 << FixItHint::CreateReplacement(Loc, CorrectedStr);
Hans Wennborg70a13242011-12-08 15:56:07 +00007659
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007660 if (Func->getLocation().isValid()
7661 && !II.getName().startswith("__builtin_"))
7662 Diag(Func->getLocation(), diag::note_previous_decl)
7663 << CorrectedQuotedStr;
Hans Wennborg70a13242011-12-08 15:56:07 +00007664 }
Hans Wennborg2fb8b912011-12-06 09:46:12 +00007665 }
7666
Chris Lattnerac18be92006-11-20 06:49:47 +00007667 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00007668 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00007669 AttributeFactory attrFactory;
7670 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00007671 unsigned DiagID;
7672 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007673 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00007674 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00007675 Declarator D(DS, Declarator::BlockContext);
John McCall084e83d2011-03-24 11:26:52 +00007676 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00007677 0, 0, true, SourceLocation(),
Douglas Gregore248eea2011-10-19 06:04:55 +00007678 SourceLocation(), SourceLocation(),
Douglas Gregorad69e652011-07-13 21:47:47 +00007679 SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00007680 EST_None, SourceLocation(),
Richard Smith2331bbf2012-05-02 22:22:32 +00007681 0, 0, 0, 0, Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00007682 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00007683 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00007684 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00007685
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00007686 // Insert this function into translation-unit scope.
7687
7688 DeclContext *PrevDC = CurContext;
7689 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00007690
John McCall48871652010-08-21 09:40:31 +00007691 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00007692 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00007693
7694 CurContext = PrevDC;
7695
Douglas Gregore711f702009-02-14 18:57:46 +00007696 AddKnownFunctionAttributes(FD);
7697
Steve Naroff3913ea42008-04-04 14:32:09 +00007698 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00007699}
7700
Douglas Gregore711f702009-02-14 18:57:46 +00007701/// \brief Adds any function attributes that we know a priori based on
7702/// the declaration of this function.
7703///
7704/// These attributes can apply both to implicitly-declared builtins
7705/// (like __builtin___printf_chk) or to library-declared functions
7706/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00007707///
7708/// We need to check for duplicate attributes both here and where user-written
7709/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00007710void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7711 if (FD->isInvalidDecl())
7712 return;
7713
7714 // If this is a built-in function, map its builtin attributes to
7715 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00007716 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00007717 // Handle printf-formatting attributes.
7718 unsigned FormatIdx;
7719 bool HasVAListArg;
7720 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007721 if (!FD->getAttr<FormatAttr>()) {
7722 const char *fmt = "printf";
7723 unsigned int NumParams = FD->getNumParams();
7724 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7725 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7726 fmt = "NSString";
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007727 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007728 fmt, FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00007729 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007730 }
Douglas Gregore711f702009-02-14 18:57:46 +00007731 }
Ted Kremenek5932c352010-07-16 02:11:15 +00007732 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7733 HasVAListArg)) {
7734 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007735 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7736 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00007737 HasVAListArg ? 0 : FormatIdx+2));
7738 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00007739
7740 // Mark const if we don't care about errno and that is the only
7741 // thing preventing the function from being const. This allows
7742 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007743 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00007744 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007745 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007746 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00007747 }
Mike Stumpca6c8752009-07-27 19:14:18 +00007748
Rafael Espindola2d21ab02011-10-12 19:51:18 +00007749 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7750 !FD->getAttr<ReturnsTwiceAttr>())
7751 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00007752 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007753 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00007754 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007755 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00007756 }
7757
7758 IdentifierInfo *Name = FD->getIdentifier();
7759 if (!Name)
7760 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007761 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00007762 FD->getDeclContext()->isTranslationUnit()) ||
7763 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00007764 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00007765 LinkageSpecDecl::lang_c)) {
7766 // Okay: this could be a libc/libm/Objective-C function we know
7767 // about.
7768 } else
7769 return;
7770
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007771 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00007772 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00007773 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007774 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007775 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7776 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00007777 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00007778 }
Douglas Gregore711f702009-02-14 18:57:46 +00007779}
Chris Lattner302b4be2006-11-19 02:31:38 +00007780
John McCall703a3f82009-10-24 08:00:42 +00007781TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00007782 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00007783 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00007784 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00007785
John McCallbcd03502009-12-07 02:54:59 +00007786 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00007787 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00007788 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00007789 }
7790
Chris Lattner18b19622007-01-22 07:39:13 +00007791 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00007792 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007793 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00007794 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00007795 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00007796 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00007797
John McCall04fcd0d2011-02-01 08:20:08 +00007798 // Bail out immediately if we have an invalid declaration.
7799 if (D.isInvalidType()) {
7800 NewTD->setInvalidDecl();
7801 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00007802 }
7803
Douglas Gregor41866812011-09-12 18:37:38 +00007804 if (D.getDeclSpec().isModulePrivateSpecified()) {
7805 if (CurContext->isFunctionOrMethod())
7806 Diag(NewTD->getLocation(), diag::err_module_private_local)
7807 << 2 << NewTD->getDeclName()
7808 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7809 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7810 else
7811 NewTD->setModulePrivate();
7812 }
Douglas Gregor26701a42011-09-09 02:06:17 +00007813
John McCall04fcd0d2011-02-01 08:20:08 +00007814 // C++ [dcl.typedef]p8:
7815 // If the typedef declaration defines an unnamed class (or
7816 // enum), the first typedef-name declared by the declaration
7817 // to be that class type (or enum type) is used to denote the
7818 // class type (or enum type) for linkage purposes only.
7819 // We need to check whether the type was declared in the declaration.
7820 switch (D.getDeclSpec().getTypeSpecType()) {
7821 case TST_enum:
7822 case TST_struct:
7823 case TST_union:
7824 case TST_class: {
7825 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7826
7827 // Do nothing if the tag is not anonymous or already has an
7828 // associated typedef (from an earlier typedef in this decl group).
7829 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00007830 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00007831
7832 // A well-formed anonymous tag must always be a TUK_Definition.
7833 assert(tagFromDeclSpec->isThisDeclarationADefinition());
7834
7835 // The type must match the tag exactly; no qualifiers allowed.
7836 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7837 break;
7838
7839 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00007840 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00007841 break;
7842 }
7843
7844 default:
7845 break;
7846 }
7847
Steve Narofff93b6722007-08-28 20:14:24 +00007848 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00007849}
7850
Douglas Gregord9034f02009-05-14 16:41:31 +00007851
Richard Smith4b38ded2012-03-14 23:13:10 +00007852/// \brief Check that this is a valid underlying type for an enum declaration.
7853bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
7854 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7855 QualType T = TI->getType();
7856
7857 if (T->isDependentType() || T->isIntegralType(Context))
7858 return false;
7859
7860 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
7861 return true;
7862}
7863
7864/// Check whether this is a valid redeclaration of a previous enumeration.
7865/// \return true if the redeclaration was invalid.
7866bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
7867 QualType EnumUnderlyingTy,
7868 const EnumDecl *Prev) {
7869 bool IsFixed = !EnumUnderlyingTy.isNull();
7870
7871 if (IsScoped != Prev->isScoped()) {
7872 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
7873 << Prev->isScoped();
7874 Diag(Prev->getLocation(), diag::note_previous_use);
7875 return true;
7876 }
7877
7878 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +00007879 if (!EnumUnderlyingTy->isDependentType() &&
7880 !Prev->getIntegerType()->isDependentType() &&
7881 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +00007882 Prev->getIntegerType())) {
7883 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
7884 << EnumUnderlyingTy << Prev->getIntegerType();
7885 Diag(Prev->getLocation(), diag::note_previous_use);
7886 return true;
7887 }
7888 } else if (IsFixed != Prev->isFixed()) {
7889 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
7890 << Prev->isFixed();
7891 Diag(Prev->getLocation(), diag::note_previous_use);
7892 return true;
7893 }
7894
7895 return false;
7896}
7897
Douglas Gregord9034f02009-05-14 16:41:31 +00007898/// \brief Determine whether a tag with a given kind is acceptable
7899/// as a redeclaration of the given tag declaration.
7900///
7901/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00007902bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00007903 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00007904 SourceLocation NewTagLoc,
7905 const IdentifierInfo &Name) {
7906 // C++ [dcl.type.elab]p3:
7907 // The class-key or enum keyword present in the
7908 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00007909 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00007910 // refers. This rule also applies to the form of
7911 // elaborated-type-specifier that declares a class-name or
7912 // friend class since it can be construed as referring to the
7913 // definition of the class. Thus, in any
7914 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00007915 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00007916 // used to refer to a union (clause 9), and either the class or
7917 // struct class-key shall be used to refer to a class (clause 9)
7918 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007919 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieucaa33d32011-06-10 03:11:26 +00007920 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7921 if (OldTag == NewTag)
7922 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007923
Abramo Bagnara6150c882010-05-11 21:36:43 +00007924 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7925 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00007926 // Warn about the struct/class tag mismatch.
7927 bool isTemplate = false;
7928 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7929 isTemplate = Record->getDescribedClassTemplate();
7930
Richard Trieucaa33d32011-06-10 03:11:26 +00007931 if (!ActiveTemplateInstantiations.empty()) {
7932 // In a template instantiation, do not offer fix-its for tag mismatches
7933 // since they usually mess up the template instead of fixing the problem.
7934 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7935 << (NewTag == TTK_Class) << isTemplate << &Name;
7936 return true;
7937 }
7938
7939 if (isDefinition) {
7940 // On definitions, check previous tags and issue a fix-it for each
7941 // one that doesn't match the current tag.
7942 if (Previous->getDefinition()) {
7943 // Don't suggest fix-its for redefinitions.
7944 return true;
7945 }
7946
7947 bool previousMismatch = false;
7948 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7949 E(Previous->redecls_end()); I != E; ++I) {
7950 if (I->getTagKind() != NewTag) {
7951 if (!previousMismatch) {
7952 previousMismatch = true;
7953 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7954 << (NewTag == TTK_Class) << isTemplate << &Name;
7955 }
7956 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7957 << (NewTag == TTK_Class)
7958 << FixItHint::CreateReplacement(I->getInnerLocStart(),
7959 NewTag == TTK_Class?
7960 "class" : "struct");
7961 }
7962 }
7963 return true;
7964 }
7965
7966 // Check for a previous definition. If current tag and definition
7967 // are same type, do nothing. If no definition, but disagree with
7968 // with previous tag type, give a warning, but no fix-it.
7969 const TagDecl *Redecl = Previous->getDefinition() ?
7970 Previous->getDefinition() : Previous;
7971 if (Redecl->getTagKind() == NewTag) {
7972 return true;
7973 }
7974
Douglas Gregord9034f02009-05-14 16:41:31 +00007975 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007976 << (NewTag == TTK_Class)
Richard Trieucaa33d32011-06-10 03:11:26 +00007977 << isTemplate << &Name;
7978 Diag(Redecl->getLocation(), diag::note_previous_use);
7979
7980 // If there is a previous defintion, suggest a fix-it.
7981 if (Previous->getDefinition()) {
7982 Diag(NewTagLoc, diag::note_struct_class_suggestion)
7983 << (Redecl->getTagKind() == TTK_Class)
7984 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7985 Redecl->getTagKind() == TTK_Class? "class" : "struct");
7986 }
7987
Douglas Gregord9034f02009-05-14 16:41:31 +00007988 return true;
7989 }
7990 return false;
7991}
7992
Steve Naroff30d242c2007-09-15 18:49:24 +00007993/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00007994/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00007995/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00007996/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00007997Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00007998 SourceLocation KWLoc, CXXScopeSpec &SS,
7999 IdentifierInfo *Name, SourceLocation NameLoc,
8000 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00008001 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +00008002 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00008003 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +00008004 SourceLocation ScopedEnumKWLoc,
8005 bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00008006 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008007 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008008 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +00008009 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00008010 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00008011 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008012
Douglas Gregord6ab8742009-05-28 23:31:59 +00008013 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00008014 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +00008015 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +00008016
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008017 // FIXME: Check explicit specializations more carefully.
8018 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008019 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00008020
8021 // We only need to do this matching if we have template parameters
8022 // or a scope specifier, which also conveniently avoids this work
8023 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00008024 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00008025 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00008026 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008027 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00008028 TemplateParameterLists.get(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00008029 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00008030 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008031 isExplicitSpecialization,
8032 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00008033 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00008034 // This is a declaration or definition of a class template (which may
8035 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00008036
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008037 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00008038 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008039
Douglas Gregore93e46c2009-07-22 23:48:44 +00008040 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00008041 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00008042 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008043 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00008044 ModulePrivateLoc,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008045 TemplateParameterLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008046 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00008047 return Result.get();
8048 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008049 // The "template<>" header is extraneous.
8050 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008051 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008052 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00008053 }
Mike Stump11289f42009-09-09 15:08:12 +00008054 }
8055 }
8056
Douglas Gregor0bf31402010-10-08 23:50:27 +00008057 // Figure out the underlying type if this a enum declaration. We need to do
8058 // this early, because it's needed to detect if this is an incompatible
8059 // redeclaration.
8060 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8061
8062 if (Kind == TTK_Enum) {
8063 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8064 // No underlying type explicitly specified, or we failed to parse the
8065 // type, default to int.
8066 EnumUnderlying = Context.IntTy.getTypePtr();
8067 else if (UnderlyingType.get()) {
8068 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8069 // integral type; any cv-qualification is ignored.
8070 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +00008071 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008072 EnumUnderlying = TI;
8073
Richard Smith4b38ded2012-03-14 23:13:10 +00008074 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +00008075 // Recover by falling back to int.
8076 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008077
Richard Smith4b38ded2012-03-14 23:13:10 +00008078 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008079 UPPC_FixedUnderlyingType))
8080 EnumUnderlying = Context.IntTy.getTypePtr();
8081
David Blaikiebbafb8a2012-03-11 07:00:24 +00008082 } else if (getLangOpts().MicrosoftMode)
Francois Picheta3108062010-10-18 15:01:13 +00008083 // Microsoft enums are always of int type.
8084 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008085 }
8086
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008087 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008088 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00008089 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00008090
Chandler Carrutha419dbb2010-03-01 21:17:36 +00008091 RedeclarationKind Redecl = ForRedeclaration;
8092 if (TUK == TUK_Friend || TUK == TUK_Reference)
8093 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00008094
8095 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00008096
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008097 if (Name && SS.isNotEmpty()) {
8098 // We have a nested-name tag ('struct foo::bar').
8099
8100 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008101 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008102 Name = 0;
8103 goto CreateNewDecl;
8104 }
8105
John McCall7f41d982009-09-11 04:59:25 +00008106 // If this is a friend or a reference to a class in a dependent
8107 // context, don't try to make a decl for it.
8108 if (TUK == TUK_Friend || TUK == TUK_Reference) {
8109 DC = computeDeclContext(SS, false);
8110 if (!DC) {
8111 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00008112 return 0;
John McCall7f41d982009-09-11 04:59:25 +00008113 }
John McCall0b66eb32010-05-01 00:40:08 +00008114 } else {
8115 DC = computeDeclContext(SS, true);
8116 if (!DC) {
8117 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8118 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008119 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00008120 }
John McCall7f41d982009-09-11 04:59:25 +00008121 }
8122
John McCall0b66eb32010-05-01 00:40:08 +00008123 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00008124 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008125
Douglas Gregor8761da52009-02-03 00:34:39 +00008126 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008127 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00008128 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00008129
John McCall1f82f242009-11-18 22:49:29 +00008130 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008131 return 0;
John McCall6538c932009-10-10 05:48:19 +00008132
John McCall1f82f242009-11-18 22:49:29 +00008133 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00008134 // Name lookup did not find anything. However, if the
8135 // nested-name-specifier refers to the current instantiation,
8136 // and that current instantiation has any dependent base
8137 // classes, we might find something at instantiation time: treat
8138 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00008139 // But this only makes any sense for reference-like lookups.
8140 if (Previous.wasNotFoundInCurrentInstantiation() &&
8141 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00008142 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00008143 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00008144 }
8145
8146 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00008147 Diag(NameLoc, diag::err_not_tag_in_scope)
8148 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008149 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008150 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008151 goto CreateNewDecl;
8152 }
Chris Lattnerd9773512009-01-21 02:38:50 +00008153 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008154 // If this is a named struct, check to see if there was a previous forward
8155 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00008156 // FIXME: We're looking into outer scopes here, even when we
8157 // shouldn't be. Doing so can result in ambiguities that we
8158 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00008159 LookupName(Previous, S);
8160
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00008161 if (Previous.isAmbiguous() &&
8162 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00008163 LookupResult::Filter F = Previous.makeFilter();
8164 while (F.hasNext()) {
8165 NamedDecl *ND = F.next();
8166 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8167 F.erase();
8168 }
8169 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00008170 }
8171
John McCall1f82f242009-11-18 22:49:29 +00008172 // Note: there used to be some attempt at recovery here.
8173 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008174 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008175
David Blaikiebbafb8a2012-03-11 07:00:24 +00008176 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008177 // FIXME: This makes sure that we ignore the contexts associated
8178 // with C structs, unions, and enums when looking for a matching
8179 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00008180 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008181 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8182 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008183 }
Douglas Gregor009f6992010-09-16 23:58:57 +00008184 } else if (S->isFunctionPrototypeScope()) {
8185 // If this is an enum declaration in function prototype scope, set its
8186 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +00008187 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +00008188 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008189 }
8190
John McCall1f82f242009-11-18 22:49:29 +00008191 if (Previous.isSingleResult() &&
8192 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00008193 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00008194 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00008195 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00008196 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00008197 }
8198
David Blaikiebbafb8a2012-03-11 07:00:24 +00008199 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008200 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008201 // This is a declaration of or a reference to "std::bad_alloc".
8202 isStdBadAlloc = true;
8203
John McCall1f82f242009-11-18 22:49:29 +00008204 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008205 // std::bad_alloc has been implicitly declared (but made invisible to
8206 // name lookup). Fill in this implicit declaration as the previous
8207 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008208 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00008209 }
8210 }
John McCall1f82f242009-11-18 22:49:29 +00008211
John McCalle9eaf8e2010-03-25 21:28:06 +00008212 // If we didn't find a previous declaration, and this is a reference
8213 // (or friend reference), move to the correct scope. In C++, we
8214 // also need to do a redeclaration lookup there, just in case
8215 // there's a shadow friend decl.
8216 if (Name && Previous.empty() &&
8217 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8218 if (Invalid) goto CreateNewDecl;
8219 assert(SS.isEmpty());
8220
8221 if (TUK == TUK_Reference) {
8222 // C++ [basic.scope.pdecl]p5:
8223 // -- for an elaborated-type-specifier of the form
8224 //
8225 // class-key identifier
8226 //
8227 // if the elaborated-type-specifier is used in the
8228 // decl-specifier-seq or parameter-declaration-clause of a
8229 // function defined in namespace scope, the identifier is
8230 // declared as a class-name in the namespace that contains
8231 // the declaration; otherwise, except as a friend
8232 // declaration, the identifier is declared in the smallest
8233 // non-class, non-function-prototype scope that contains the
8234 // declaration.
8235 //
8236 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8237 // C structs and unions.
8238 //
8239 // It is an error in C++ to declare (rather than define) an enum
8240 // type, including via an elaborated type specifier. We'll
8241 // diagnose that later; for now, declare the enum in the same
8242 // scope as we would have picked for any other tag type.
8243 //
8244 // GNU C also supports this behavior as part of its incomplete
8245 // enum types extension, while GNU C++ does not.
8246 //
8247 // Find the context where we'll be declaring the tag.
8248 // FIXME: We would like to maintain the current DeclContext as the
8249 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +00008250 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +00008251 SearchDC = SearchDC->getParent();
8252
8253 // Find the scope where we'll be declaring the tag.
8254 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008255 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +00008256 S->isFunctionPrototypeScope()) ||
8257 ((S->getFlags() & Scope::DeclScope) == 0) ||
8258 (S->getEntity() &&
8259 ((DeclContext *)S->getEntity())->isTransparentContext()))
8260 S = S->getParent();
8261 } else {
8262 assert(TUK == TUK_Friend);
8263 // C++ [namespace.memdef]p3:
8264 // If a friend declaration in a non-local class first declares a
8265 // class or function, the friend class or function is a member of
8266 // the innermost enclosing namespace.
8267 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00008268 }
8269
John McCalle87beb22010-04-23 18:46:30 +00008270 // In C++, we need to do a redeclaration lookup to properly
8271 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008272 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +00008273 Previous.setRedeclarationKind(ForRedeclaration);
8274 LookupQualifiedName(Previous, SearchDC);
8275 }
8276 }
8277
John McCall1f82f242009-11-18 22:49:29 +00008278 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00008279 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00008280
8281 // It's okay to have a tag decl in the same scope as a typedef
8282 // which hides a tag decl in the same scope. Finding this
8283 // insanity with a redeclaration lookup can only actually happen
8284 // in C++.
8285 //
8286 // This is also okay for elaborated-type-specifiers, which is
8287 // technically forbidden by the current standard but which is
8288 // okay according to the likely resolution of an open issue;
8289 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +00008290 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00008291 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00008292 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8293 TagDecl *Tag = TT->getDecl();
8294 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008295 Tag->getDeclContext()->getRedeclContext()
8296 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00008297 PrevDecl = Tag;
8298 Previous.clear();
8299 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00008300 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00008301 }
8302 }
8303 }
8304 }
8305
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008306 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00008307 // If this is a use of a previous tag, or if the tag is already declared
8308 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008309 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00008310 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00008311 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00008312 // Make sure that this wasn't declared as an enum and now used as a
8313 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00008314 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8315 TUK == TUK_Definition, KWLoc,
8316 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00008317 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00008318 = (PrevTagDecl->getTagKind() != TTK_Enum &&
8319 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00008320 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00008321 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00008322 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00008323 << FixItHint::CreateReplacement(SourceRange(KWLoc),
8324 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00008325 else
8326 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00008327 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00008328
Mike Stump11289f42009-09-09 15:08:12 +00008329 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00008330 Kind = PrevTagDecl->getTagKind();
8331 else {
8332 // Recover by making this an anonymous redefinition.
8333 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008334 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00008335 Invalid = true;
8336 }
8337 }
8338
Douglas Gregor0bf31402010-10-08 23:50:27 +00008339 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8340 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8341
Richard Smith0f8ee222012-01-10 01:33:14 +00008342 // If this is an elaborated-type-specifier for a scoped enumeration,
8343 // the 'class' keyword is not necessary and not permitted.
8344 if (TUK == TUK_Reference || TUK == TUK_Friend) {
8345 if (ScopedEnum)
8346 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8347 << PrevEnum->isScoped()
8348 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8349 return PrevTagDecl;
8350 }
8351
Richard Smith4b38ded2012-03-14 23:13:10 +00008352 QualType EnumUnderlyingTy;
8353 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8354 EnumUnderlyingTy = TI->getType();
8355 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8356 EnumUnderlyingTy = QualType(T, 0);
8357
Douglas Gregor0bf31402010-10-08 23:50:27 +00008358 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +00008359 // returning the previous declaration, unless this is a definition,
8360 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +00008361 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8362 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +00008363 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +00008364 }
8365
Douglas Gregor170512f2009-04-01 23:51:29 +00008366 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008367 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00008368
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008369 // FIXME: In the future, return a variant or some other clue
8370 // for the consumer of this Decl to know it doesn't own it.
8371 // For our current ASTs this shouldn't be a problem, but will
8372 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00008373 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008374 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00008375 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008376
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008377 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00008378 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008379 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008380 // If we're defining a specialization and the previous definition
8381 // is from an implicit instantiation, don't emit an error
8382 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +00008383 bool IsExplicitSpecializationAfterInstantiation = false;
8384 if (isExplicitSpecialization) {
8385 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8386 IsExplicitSpecializationAfterInstantiation =
8387 RD->getTemplateSpecializationKind() !=
8388 TSK_ExplicitSpecialization;
8389 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8390 IsExplicitSpecializationAfterInstantiation =
8391 ED->getTemplateSpecializationKind() !=
8392 TSK_ExplicitSpecialization;
8393 }
8394
8395 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +00008396 // A redeclaration in function prototype scope in C isn't
8397 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008398 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +00008399 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8400 else
8401 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008402 Diag(Def->getLocation(), diag::note_previous_definition);
8403 // If this is a redefinition, recover by making this
8404 // struct be anonymous, which will make any later
8405 // references get the previous definition.
8406 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008407 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008408 Invalid = true;
8409 }
Douglas Gregordee1be82009-01-17 00:42:38 +00008410 } else {
8411 // If the type is currently being defined, complain
8412 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00008413 const TagType *Tag
8414 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00008415 if (Tag->isBeingDefined()) {
8416 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00008417 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00008418 diag::note_previous_definition);
8419 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008420 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00008421 Invalid = true;
8422 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008423 }
Douglas Gregordee1be82009-01-17 00:42:38 +00008424
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008425 // Okay, this is definition of a previously declared or referenced
8426 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00008427 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008428 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008429 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00008430 // have a definition. Just create a new decl.
8431
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008432 } else {
8433 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00008434 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008435 // new decl/type. We set PrevDecl to NULL so that the entities
8436 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00008437 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00008438 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008439 // If we get here, we're going to create a new Decl. If PrevDecl
8440 // is non-NULL, it's a definition of the tag declared by
8441 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00008442
8443
8444 // Otherwise, PrevDecl is not a tag, but was found with tag
8445 // lookup. This is only actually possible in C++, where a few
8446 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008447 } else {
John McCalle87beb22010-04-23 18:46:30 +00008448 // Use a better diagnostic if an elaborated-type-specifier
8449 // found the wrong kind of type on the first
8450 // (non-redeclaration) lookup.
8451 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8452 !Previous.isForRedeclaration()) {
8453 unsigned Kind = 0;
8454 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00008455 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8456 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00008457 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8458 Diag(PrevDecl->getLocation(), diag::note_declared_at);
8459 Invalid = true;
8460
8461 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00008462 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8463 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00008464 // do nothing
8465
8466 // Diagnose implicit declarations introduced by elaborated types.
8467 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8468 unsigned Kind = 0;
8469 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00008470 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8471 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00008472 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8473 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8474 Invalid = true;
8475
8476 // Otherwise it's a declaration. Call out a particularly common
8477 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00008478 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8479 unsigned Kind = 0;
8480 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00008481 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00008482 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00008483 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8484 Invalid = true;
8485
8486 // Otherwise, diagnose.
8487 } else {
8488 // The tag name clashes with something else in the target scope,
8489 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008490 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00008491 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00008492 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00008493 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00008494 }
John McCalle87beb22010-04-23 18:46:30 +00008495
8496 // The existing declaration isn't relevant to us; we're in a
8497 // new scope, so clear out the previous declaration.
8498 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00008499 }
Chris Lattner18b19622007-01-22 07:39:13 +00008500 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00008501
Chris Lattner438e5012008-12-17 07:13:27 +00008502CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00008503
John McCall1f82f242009-11-18 22:49:29 +00008504 TagDecl *PrevDecl = 0;
8505 if (Previous.isSingleResult())
8506 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8507
Chris Lattnerbf0b7982007-01-23 04:27:41 +00008508 // If there is an identifier, use the location of the identifier as the
8509 // location of the decl, otherwise use the location of the struct/union
8510 // keyword.
8511 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00008512
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008513 // Otherwise, create a new declaration. If there is a previous
8514 // declaration of the same entity, the two will be linked via
8515 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00008516 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00008517
Douglas Gregor0bf31402010-10-08 23:50:27 +00008518 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00008519 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00008520 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8521 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008522 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00008523 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00008524 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00008525 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00008526 if (TUK != TUK_Definition && !Invalid) {
8527 TagDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008528 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00008529 // C++0x: 7.2p2: opaque-enum-declaration.
8530 // Conflicts are diagnosed above. Do nothing.
8531 }
8532 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00008533 Diag(Loc, diag::ext_forward_ref_enum_def)
8534 << New;
8535 Diag(Def->getLocation(), diag::note_previous_definition);
8536 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00008537 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008538 if (getLangOpts().MicrosoftMode)
Francois Pichet488b4a72010-09-12 05:06:55 +00008539 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008540 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +00008541 DiagID = diag::err_forward_ref_enum;
8542 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008543
8544 // If this is a forward-declared reference to an enumeration, make a
8545 // note of it; we won't actually be introducing the declaration into
8546 // the declaration context.
8547 if (TUK == TUK_Reference)
8548 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00008549 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00008550 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00008551
8552 if (EnumUnderlying) {
8553 EnumDecl *ED = cast<EnumDecl>(New);
8554 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8555 ED->setIntegerTypeSourceInfo(TI);
8556 else
8557 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8558 ED->setPromotionType(ED->getIntegerType());
8559 }
8560
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00008561 } else {
8562 // struct/union/class
8563
Chris Lattner776fac82007-06-09 00:53:06 +00008564 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8565 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008566 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00008567 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008568 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008569 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008570
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008571 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00008572 StdBadAlloc = cast<CXXRecordDecl>(New);
8573 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008574 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008575 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00008576 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008577
John McCall3e11ebe2010-03-15 10:12:16 +00008578 // Maybe add qualifier info.
8579 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00008580 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008581 // If this is either a declaration or a definition, check the
8582 // nested-name-specifier against the current context. We don't do this
8583 // for explicit specializations, because they have similar checking
8584 // (with more specific diagnostics) in the call to
8585 // CheckMemberSpecialization, below.
8586 if (!isExplicitSpecialization &&
8587 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
8588 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
8589 Invalid = true;
8590
Douglas Gregor14454802011-02-25 02:25:35 +00008591 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00008592 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00008593 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008594 TemplateParameterLists.size(),
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00008595 (TemplateParameterList**) TemplateParameterLists.release());
8596 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00008597 }
8598 else
8599 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00008600 }
8601
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00008602 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8603 // Add alignment attributes if necessary; these attributes are checked when
8604 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008605 //
8606 // It is important for implementing the correct semantics that this
8607 // happen here (in act on tag decl). The #pragma pack stack is
8608 // maintained as a result of parser callbacks which can occur at
8609 // many points during the parsing of a struct declaration (because
8610 // the #pragma tokens are effectively skipped over during the
8611 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00008612 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +00008613
8614 AddMsStructLayoutForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008615 }
8616
Douglas Gregor21823bf2011-12-20 18:11:52 +00008617 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00008618 if (isExplicitSpecialization)
8619 Diag(New->getLocation(), diag::err_module_private_specialization)
8620 << 2
8621 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +00008622 // __module_private__ does not apply to local classes. However, we only
8623 // diagnose this as an error when the declaration specifiers are
8624 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +00008625 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +00008626 New->setModulePrivate();
8627 }
8628
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008629 // If this is a specialization of a member class (of a class template),
8630 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00008631 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008632 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008633
Douglas Gregordee1be82009-01-17 00:42:38 +00008634 if (Invalid)
8635 New->setInvalidDecl();
8636
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008637 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00008638 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008639
Douglas Gregordee1be82009-01-17 00:42:38 +00008640 // If we're declaring or defining a tag in function prototype scope
8641 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008642 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +00008643 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8644
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008645 // Set the lexical context. If the tag has a C++ scope specifier, the
8646 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00008647 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00008648
John McCallaa74a0c2009-08-28 07:59:38 +00008649 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00008650 // In Microsoft mode, a friend declaration also acts as a forward
8651 // declaration so we always pass true to setObjectOfFriendDecl to make
8652 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00008653 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00008654 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008655 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +00008656
Anders Carlsson5558ca12009-03-26 01:19:02 +00008657 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00008658 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008659 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00008660
John McCall9bb74a52009-07-31 02:45:11 +00008661 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00008662 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00008663
Chris Lattner18b19622007-01-22 07:39:13 +00008664 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00008665 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00008666 // We might be replacing an existing declaration in the lookup tables;
8667 // if so, borrow its access specifier.
8668 if (PrevDecl)
8669 New->setAccess(PrevDecl->getAccess());
8670
Sebastian Redl50c68252010-08-31 00:36:30 +00008671 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00008672 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +00008673 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00008674 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8675 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00008676 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00008677 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008678 PushOnScopeChains(New, S, !IsForwardReference);
8679 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +00008680 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008681
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008682 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008683 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00008684 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00008685
Douglas Gregor27821ce2009-07-07 16:35:42 +00008686 // If this is the C FILE type, notify the AST context.
8687 if (IdentifierInfo *II = New->getIdentifier())
8688 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008689 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00008690 II->isStr("FILE"))
8691 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00008692
James Molloy6f8780b2012-02-29 10:24:19 +00008693 // If we were in function prototype scope (and not in C++ mode), add this
8694 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008695 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +00008696 InFunctionDeclarator && Name)
8697 DeclsInPrototypeScope.push_back(New);
8698
Douglas Gregord6ab8742009-05-28 23:31:59 +00008699 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00008700 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00008701}
Chris Lattner1300fb92007-01-23 23:42:53 +00008702
John McCall48871652010-08-21 09:40:31 +00008703void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008704 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008705 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00008706
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008707 // Enter the tag context.
8708 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00008709}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008710
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008711Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008712 assert(isa<ObjCContainerDecl>(IDecl) &&
8713 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8714 DeclContext *OCD = cast<DeclContext>(IDecl);
8715 assert(getContainingDC(OCD) == CurContext &&
8716 "The next DeclContext should be lexically contained in the current one.");
8717 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008718 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008719}
8720
John McCall48871652010-08-21 09:40:31 +00008721void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00008722 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00008723 SourceLocation LBraceLoc) {
8724 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008725 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008726
John McCall1c7e6ec2009-12-20 07:58:13 +00008727 FieldCollector->StartClass();
8728
8729 if (!Record->getIdentifier())
8730 return;
8731
Anders Carlsson30f29442011-03-25 14:31:08 +00008732 if (FinalLoc.isValid())
8733 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00008734
John McCall1c7e6ec2009-12-20 07:58:13 +00008735 // C++ [class]p2:
8736 // [...] The class-name is also inserted into the scope of the
8737 // class itself; this is known as the injected-class-name. For
8738 // purposes of access checking, the injected-class-name is treated
8739 // as if it were a public member name.
8740 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008741 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8742 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00008743 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00008744 /*PrevDecl=*/0,
8745 /*DelayTypeCreation=*/true);
8746 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00008747 InjectedClassName->setImplicit();
8748 InjectedClassName->setAccess(AS_public);
8749 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8750 InjectedClassName->setDescribedClassTemplate(Template);
8751 PushOnScopeChains(InjectedClassName, S);
8752 assert(InjectedClassName->isInjectedClassName() &&
8753 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008754}
8755
John McCall48871652010-08-21 09:40:31 +00008756void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00008757 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008758 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008759 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00008760 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008761
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00008762 // Make sure we "complete" the definition even it is invalid.
8763 if (Tag->isBeingDefined()) {
8764 assert(Tag->isInvalidDecl() && "We should already have completed it");
8765 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8766 RD->completeDefinition();
8767 }
8768
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008769 if (isa<CXXRecordDecl>(Tag))
8770 FieldCollector->FinishClass();
8771
8772 // Exit this scope of this tag's definition.
8773 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00008774
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008775 // Notify the consumer that we've defined a tag.
8776 Consumer.HandleTagDeclDefinition(Tag);
8777}
Chris Lattner535b8302008-06-21 19:39:06 +00008778
Fariborz Jahanian4327b322011-08-29 17:33:12 +00008779void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008780 // Exit this scope of this interface definition.
8781 PopDeclContext();
8782}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008783
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +00008784void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +00008785 assert(DC == CurContext && "Mismatch of container contexts");
8786 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008787 ActOnObjCContainerFinishDefinition();
8788}
8789
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +00008790void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8791 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008792 OriginalLexicalContext = 0;
8793}
8794
John McCall48871652010-08-21 09:40:31 +00008795void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00008796 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008797 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00008798 Tag->setInvalidDecl();
8799
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00008800 // Make sure we "complete" the definition even it is invalid.
8801 if (Tag->isBeingDefined()) {
8802 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8803 RD->completeDefinition();
8804 }
8805
John McCall71ba5f22010-03-17 19:25:57 +00008806 // We're undoing ActOnTagStartDefinition here, not
8807 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8808 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00008809
8810 PopDeclContext();
8811}
8812
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008813// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +00008814ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
8815 IdentifierInfo *FieldName,
8816 QualType FieldTy, Expr *BitWidth,
8817 bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +00008818 // Default to true; that shouldn't confuse checks for emptiness
8819 if (ZeroWidth)
8820 *ZeroWidth = true;
8821
Chris Lattner73bf7b42009-03-05 22:45:59 +00008822 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00008823 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00008824 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00008825 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00008826 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +00008827 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008828 if (FieldName)
8829 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8830 << FieldName << FieldTy << BitWidth->getSourceRange();
8831 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8832 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00008833 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8834 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +00008835 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +00008836
8837 // If the bit-width is type- or value-dependent, don't try to check
8838 // it now.
8839 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +00008840 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +00008841
Anders Carlsson5df391e2008-12-06 20:33:04 +00008842 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00008843 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
8844 if (ICE.isInvalid())
8845 return ICE;
8846 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +00008847
Eli Friedmanc96d4962009-08-15 21:55:26 +00008848 if (Value != 0 && ZeroWidth)
8849 *ZeroWidth = false;
8850
Chris Lattner81ed6802008-12-12 04:56:04 +00008851 // Zero-width bitfield is ok for anonymous field.
8852 if (Value == 0 && FieldName)
8853 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00008854
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008855 if (Value.isSigned() && Value.isNegative()) {
8856 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00008857 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008858 << FieldName << Value.toString(10);
8859 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8860 << Value.toString(10);
8861 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00008862
Douglas Gregor1efa4372009-03-11 18:59:21 +00008863 if (!FieldTy->isDependentType()) {
8864 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008865 if (Value.getZExtValue() > TypeSize) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008866 if (!getLangOpts().CPlusPlus) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00008867 if (FieldName)
8868 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8869 << FieldName << (unsigned)Value.getZExtValue()
8870 << (unsigned)TypeSize;
8871
8872 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8873 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8874 }
8875
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008876 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00008877 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8878 << FieldName << (unsigned)Value.getZExtValue()
8879 << (unsigned)TypeSize;
8880 else
8881 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8882 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00008883 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00008884 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00008885
Richard Smithf4c51d92012-02-04 09:53:13 +00008886 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +00008887}
8888
Richard Smith938f40b2011-06-11 17:19:42 +00008889/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00008890/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00008891Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00008892 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00008893 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00008894 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith938f40b2011-06-11 17:19:42 +00008895 /*HasInit=*/false, AS_public);
John McCall48871652010-08-21 09:40:31 +00008896 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00008897}
8898
8899/// HandleField - Analyze a field of a C struct or a C++ data member.
8900///
8901FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8902 SourceLocation DeclStart,
Richard Smith938f40b2011-06-11 17:19:42 +00008903 Declarator &D, Expr *BitWidth, bool HasInit,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00008904 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00008905 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00008906 SourceLocation Loc = DeclStart;
8907 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00008908
John McCall8cb7bdf2010-06-04 23:28:52 +00008909 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8910 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008911 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00008912 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00008913
Douglas Gregora02a72a2010-12-15 23:18:36 +00008914 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8915 UPPC_DataMemberType)) {
8916 D.setInvalidType();
8917 T = Context.IntTy;
8918 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8919 }
8920 }
8921
Eli Friedman574c7452009-04-07 19:37:57 +00008922 DiagnoseFunctionSpecifiers(D);
8923
Eli Friedmand5c0eed2009-04-19 20:27:55 +00008924 if (D.getDeclSpec().isThreadSpecified())
8925 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00008926 if (D.getDeclSpec().isConstexprSpecified())
8927 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8928 << 2;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00008929
8930 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +00008931 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00008932 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8933 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +00008934 switch (Previous.getResultKind()) {
8935 case LookupResult::Found:
8936 case LookupResult::FoundUnresolvedValue:
8937 PrevDecl = Previous.getAsSingle<NamedDecl>();
8938 break;
8939
8940 case LookupResult::FoundOverloaded:
8941 PrevDecl = Previous.getRepresentativeDecl();
8942 break;
8943
8944 case LookupResult::NotFound:
8945 case LookupResult::NotFoundInCurrentInstantiation:
8946 case LookupResult::Ambiguous:
8947 break;
8948 }
8949 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +00008950
8951 if (PrevDecl && PrevDecl->isTemplateParameter()) {
8952 // Maybe we will complain about the shadowed template parameter.
8953 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8954 // Just pretend that we didn't see the previous declaration.
8955 PrevDecl = 0;
8956 }
8957
Douglas Gregor1efa4372009-03-11 18:59:21 +00008958 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8959 PrevDecl = 0;
8960
Steve Naroff5ec6ff72009-07-14 14:58:18 +00008961 bool Mutable
8962 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008963 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +00008964 FieldDecl *NewFD
Richard Smith938f40b2011-06-11 17:19:42 +00008965 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8966 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00008967
8968 if (NewFD->isInvalidDecl())
8969 Record->setInvalidDecl();
8970
Douglas Gregor3baa6702011-09-12 16:11:24 +00008971 if (D.getDeclSpec().isModulePrivateSpecified())
8972 NewFD->setModulePrivate();
8973
Douglas Gregor1efa4372009-03-11 18:59:21 +00008974 if (NewFD->isInvalidDecl() && PrevDecl) {
8975 // Don't introduce NewFD into scope; there's already something
8976 // with the same name in the same scope.
8977 } else if (II) {
8978 PushOnScopeChains(NewFD, S);
8979 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008980 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00008981
8982 return NewFD;
8983}
8984
8985/// \brief Build a new FieldDecl and check its well-formedness.
8986///
8987/// This routine builds a new FieldDecl given the fields name, type,
8988/// record, etc. \p PrevDecl should refer to any previous declaration
8989/// with the same name and in the same scope as the field to be
8990/// created.
8991///
8992/// \returns a new FieldDecl.
8993///
Mike Stump11289f42009-09-09 15:08:12 +00008994/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00008995FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00008996 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00008997 RecordDecl *Record, SourceLocation Loc,
Richard Smith938f40b2011-06-11 17:19:42 +00008998 bool Mutable, Expr *BitWidth, bool HasInit,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00008999 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009000 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00009001 Declarator *D) {
9002 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00009003 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009004 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009005
Douglas Gregor1efa4372009-03-11 18:59:21 +00009006 // If we receive a broken type, recover by assuming 'int' and
9007 // marking this declaration as invalid.
9008 if (T.isNull()) {
9009 InvalidDecl = true;
9010 T = Context.IntTy;
9011 }
9012
Eli Friedmand0e8de22009-12-07 00:22:08 +00009013 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00009014 if (!EltTy->isDependentType()) {
9015 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9016 // Fields of incomplete type force their record to be invalid.
9017 Record->setInvalidDecl();
9018 InvalidDecl = true;
9019 } else {
9020 NamedDecl *Def;
9021 EltTy->isIncompleteType(&Def);
9022 if (Def && Def->isInvalidDecl()) {
9023 Record->setInvalidDecl();
9024 InvalidDecl = true;
9025 }
9026 }
John McCall2677e102010-08-16 23:42:35 +00009027 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00009028
Steve Naroff8eeeb132007-05-08 21:09:37 +00009029 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9030 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00009031 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00009032 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009033 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00009034 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009035 SizeIsNegative,
9036 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009037 if (!FixedTy.isNull()) {
9038 Diag(Loc, diag::warn_illegal_constant_array_size);
9039 T = FixedTy;
9040 } else {
9041 if (SizeIsNegative)
9042 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009043 else if (Oversized.getBoolValue())
9044 Diag(Loc, diag::err_array_too_large)
9045 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009046 else
9047 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009048 InvalidDecl = true;
9049 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00009050 }
Mike Stump11289f42009-09-09 15:08:12 +00009051
Anders Carlsson576cc6f2009-03-22 20:18:17 +00009052 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00009053 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9054 diag::err_abstract_type_in_decl,
9055 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00009056 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00009057
Eli Friedmanc96d4962009-08-15 21:55:26 +00009058 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00009059 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +00009060 if (!InvalidDecl && BitWidth) {
9061 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9062 if (!BitWidth) {
9063 InvalidDecl = true;
9064 BitWidth = 0;
9065 ZeroWidth = false;
9066 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009067 }
Mike Stump11289f42009-09-09 15:08:12 +00009068
John McCallb1cd7da2010-06-04 08:34:12 +00009069 // Check that 'mutable' is consistent with the type of the declaration.
9070 if (!InvalidDecl && Mutable) {
9071 unsigned DiagID = 0;
9072 if (T->isReferenceType())
9073 DiagID = diag::err_mutable_reference;
9074 else if (T.isConstQualified())
9075 DiagID = diag::err_mutable_const;
9076
9077 if (DiagID) {
9078 SourceLocation ErrLoc = Loc;
9079 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9080 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9081 Diag(ErrLoc, DiagID);
9082 Mutable = false;
9083 InvalidDecl = true;
9084 }
9085 }
9086
Abramo Bagnaradff19302011-03-08 08:55:46 +00009087 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00009088 BitWidth, Mutable, HasInit);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009089 if (InvalidDecl)
9090 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00009091
Douglas Gregor1efa4372009-03-11 18:59:21 +00009092 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9093 Diag(Loc, diag::err_duplicate_member) << II;
9094 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9095 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009096 }
9097
David Blaikiebbafb8a2012-03-11 07:00:24 +00009098 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00009099 if (Record->isUnion()) {
9100 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9101 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9102 if (RDecl->getDefinition()) {
9103 // C++ [class.union]p1: An object of a class with a non-trivial
9104 // constructor, a non-trivial copy constructor, a non-trivial
9105 // destructor, or a non-trivial copy assignment operator
9106 // cannot be a member of a union, nor can an array of such
9107 // objects.
Richard Smithf720df02011-10-19 20:41:51 +00009108 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00009109 NewFD->setInvalidDecl();
9110 }
9111 }
9112
9113 // C++ [class.union]p1: If a union contains a member of reference type,
9114 // the program is ill-formed.
9115 if (EltTy->isReferenceType()) {
9116 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9117 << NewFD->getDeclName() << EltTy;
9118 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00009119 }
9120 }
9121 }
9122
Douglas Gregor1efa4372009-03-11 18:59:21 +00009123 // FIXME: We need to pass in the attributes given an AST
9124 // representation, not a parser representation.
9125 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00009126 // FIXME: What to pass instead of TUScope?
9127 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009128
John McCall31168b02011-06-15 23:02:42 +00009129 // In auto-retain/release, infer strong retension for fields of
9130 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009131 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +00009132 NewFD->setInvalidDecl();
9133
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00009134 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00009135 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00009136
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009137 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00009138 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00009139}
9140
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009141bool Sema::CheckNontrivialField(FieldDecl *FD) {
9142 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009143 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009144
9145 if (FD->isInvalidDecl())
9146 return true;
9147
9148 QualType EltTy = Context.getBaseElementType(FD->getType());
9149 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9150 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9151 if (RDecl->getDefinition()) {
9152 // We check for copy constructors before constructors
9153 // because otherwise we'll never get complaints about
9154 // copy constructors.
9155
9156 CXXSpecialMember member = CXXInvalid;
9157 if (!RDecl->hasTrivialCopyConstructor())
9158 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00009159 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009160 member = CXXDefaultConstructor;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009161 else if (!RDecl->hasTrivialCopyAssignment())
9162 member = CXXCopyAssignment;
9163 else if (!RDecl->hasTrivialDestructor())
9164 member = CXXDestructor;
9165
9166 if (member != CXXInvalid) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009167 if (!getLangOpts().CPlusPlus0x &&
9168 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +00009169 // Objective-C++ ARC: it is an error to have a non-trivial field of
9170 // a union. However, system headers in Objective-C programs
9171 // occasionally have Objective-C lifetime objects within unions,
9172 // and rather than cause the program to fail, we make those
9173 // members unavailable.
9174 SourceLocation Loc = FD->getLocation();
9175 if (getSourceManager().isInSystemHeader(Loc)) {
9176 if (!FD->hasAttr<UnavailableAttr>())
9177 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009178 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00009179 return false;
9180 }
9181 }
Richard Smithf720df02011-10-19 20:41:51 +00009182
David Blaikiebbafb8a2012-03-11 07:00:24 +00009183 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
Richard Smithf720df02011-10-19 20:41:51 +00009184 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9185 diag::err_illegal_union_or_anon_struct_member)
9186 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009187 DiagnoseNontrivial(RT, member);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009188 return !getLangOpts().CPlusPlus0x;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009189 }
9190 }
9191 }
9192
9193 return false;
9194}
9195
Richard Smith8e1c9322012-02-26 10:50:32 +00009196/// If the given constructor is user-provided, produce a diagnostic explaining
9197/// that it makes the class non-trivial.
9198static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9199 CXXConstructorDecl *CD,
9200 Sema::CXXSpecialMember CSM) {
9201 if (!CD->isUserProvided())
9202 return false;
9203
9204 SourceLocation CtorLoc = CD->getLocation();
9205 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9206 return true;
9207}
9208
Douglas Gregor8a273912009-07-22 18:25:24 +00009209/// DiagnoseNontrivial - Given that a class has a non-trivial
9210/// special member, figure out why.
9211void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9212 QualType QT(T, 0U);
9213 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9214
9215 // Check whether the member was user-declared.
9216 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00009217 case CXXInvalid:
9218 break;
9219
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009220 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00009221 if (RD->hasUserDeclaredConstructor()) {
9222 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Richard Smith8e1c9322012-02-26 10:50:32 +00009223 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
David Blaikie2d7c57e2012-04-30 02:36:29 +00009224 if (DiagnoseNontrivialUserProvidedCtor(*this, QT, &*CI, member))
Douglas Gregor8a273912009-07-22 18:25:24 +00009225 return;
Douglas Gregor8a273912009-07-22 18:25:24 +00009226
Richard Smith8e1c9322012-02-26 10:50:32 +00009227 // No user-provided constructors; look for constructor templates.
9228 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9229 tmpl_iter;
9230 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9231 TI != TE; ++TI) {
9232 CXXConstructorDecl *CD =
9233 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9234 if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9235 return;
9236 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009237 }
9238 break;
9239
9240 case CXXCopyConstructor:
9241 if (RD->hasUserDeclaredCopyConstructor()) {
9242 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00009243 RD->getCopyConstructor(0)->getLocation();
9244 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9245 return;
9246 }
9247 break;
9248
9249 case CXXMoveConstructor:
9250 if (RD->hasUserDeclaredMoveConstructor()) {
9251 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009252 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9253 return;
9254 }
9255 break;
9256
9257 case CXXCopyAssignment:
9258 if (RD->hasUserDeclaredCopyAssignment()) {
9259 // FIXME: this should use the location of the copy
9260 // assignment, not the type.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009261 SourceLocation TyLoc = RD->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009262 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9263 return;
9264 }
9265 break;
9266
Alexis Huntfcaeae42011-05-25 20:50:04 +00009267 case CXXMoveAssignment:
9268 if (RD->hasUserDeclaredMoveAssignment()) {
9269 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9270 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9271 return;
9272 }
9273 break;
9274
Douglas Gregor8a273912009-07-22 18:25:24 +00009275 case CXXDestructor:
9276 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00009277 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009278 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9279 return;
9280 }
9281 break;
9282 }
9283
9284 typedef CXXRecordDecl::base_class_iterator base_iter;
9285
9286 // Virtual bases and members inhibit trivial copying/construction,
9287 // but not trivial destruction.
9288 if (member != CXXDestructor) {
9289 // Check for virtual bases. vbases includes indirect virtual bases,
9290 // so we just iterate through the direct bases.
9291 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9292 if (bi->isVirtual()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009293 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009294 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9295 return;
9296 }
9297
9298 // Check for virtual methods.
9299 typedef CXXRecordDecl::method_iterator meth_iter;
9300 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9301 ++mi) {
9302 if (mi->isVirtual()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009303 SourceLocation MLoc = mi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009304 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9305 return;
9306 }
9307 }
9308 }
Mike Stump11289f42009-09-09 15:08:12 +00009309
Douglas Gregor8a273912009-07-22 18:25:24 +00009310 bool (CXXRecordDecl::*hasTrivial)() const;
9311 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009312 case CXXDefaultConstructor:
Alexis Huntf479f1b2011-05-09 18:22:59 +00009313 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00009314 case CXXCopyConstructor:
9315 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9316 case CXXCopyAssignment:
9317 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9318 case CXXDestructor:
9319 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9320 default:
David Blaikieaa347f92011-09-23 20:26:49 +00009321 llvm_unreachable("unexpected special member");
Douglas Gregor8a273912009-07-22 18:25:24 +00009322 }
9323
9324 // Check for nontrivial bases (and recurse).
9325 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009326 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00009327 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00009328 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9329 if (!(BaseRecTy->*hasTrivial)()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009330 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009331 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9332 DiagnoseNontrivial(BaseRT, member);
9333 return;
9334 }
9335 }
Mike Stump11289f42009-09-09 15:08:12 +00009336
Douglas Gregor8a273912009-07-22 18:25:24 +00009337 // Check for nontrivial members (and recurse).
9338 typedef RecordDecl::field_iterator field_iter;
9339 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9340 ++fi) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009341 QualType EltTy = Context.getBaseElementType(fi->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009342 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00009343 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9344
9345 if (!(EltRD->*hasTrivial)()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009346 SourceLocation FLoc = fi->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009347 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9348 DiagnoseNontrivial(EltRT, member);
9349 return;
9350 }
9351 }
John McCall31168b02011-06-15 23:02:42 +00009352
9353 if (EltTy->isObjCLifetimeType()) {
9354 switch (EltTy.getObjCLifetime()) {
9355 case Qualifiers::OCL_None:
9356 case Qualifiers::OCL_ExplicitNone:
9357 break;
9358
9359 case Qualifiers::OCL_Autoreleasing:
9360 case Qualifiers::OCL_Weak:
9361 case Qualifiers::OCL_Strong:
David Blaikie2d7c57e2012-04-30 02:36:29 +00009362 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00009363 << QT << EltTy.getObjCLifetime();
9364 return;
9365 }
9366 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009367 }
9368
David Blaikie83d382b2011-09-23 05:06:16 +00009369 llvm_unreachable("found no explanation for non-trivial member");
Douglas Gregor8a273912009-07-22 18:25:24 +00009370}
9371
Mike Stump11289f42009-09-09 15:08:12 +00009372/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00009373/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00009374static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00009375TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00009376 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +00009377 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +00009378 case tok::objc_private: return ObjCIvarDecl::Private;
9379 case tok::objc_public: return ObjCIvarDecl::Public;
9380 case tok::objc_protected: return ObjCIvarDecl::Protected;
9381 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00009382 }
9383}
9384
Mike Stump11289f42009-09-09 15:08:12 +00009385/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00009386/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00009387Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00009388 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00009389 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +00009390 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00009391
Fariborz Jahaniande615832008-04-10 23:32:45 +00009392 IdentifierInfo *II = D.getIdentifier();
9393 Expr *BitWidth = (Expr*)BitfieldWidth;
9394 SourceLocation Loc = DeclStart;
9395 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00009396
Fariborz Jahaniande615832008-04-10 23:32:45 +00009397 // FIXME: Unnamed fields can be handled in various different ways, for
9398 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00009399
John McCall8cb7bdf2010-06-04 23:28:52 +00009400 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9401 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009402
Fariborz Jahaniande615832008-04-10 23:32:45 +00009403 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00009404 // 6.7.2.1p3, 6.7.2.1p4
Richard Smithf4c51d92012-02-04 09:53:13 +00009405 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9406 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009407 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00009408 } else {
9409 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00009410
Fariborz Jahaniande615832008-04-10 23:32:45 +00009411 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00009412
Fariborz Jahaniande615832008-04-10 23:32:45 +00009413 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00009414 if (T->isReferenceType()) {
9415 Diag(Loc, diag::err_ivar_reference_type);
9416 D.setInvalidType();
9417 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00009418 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9419 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00009420 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00009421 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009422 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00009423 }
Mike Stump11289f42009-09-09 15:08:12 +00009424
Ted Kremenek73295fa2008-07-23 18:04:17 +00009425 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00009426 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00009427 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9428 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00009429 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009430 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +00009431 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9432 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +00009433 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00009434 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00009435 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00009436 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00009437 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00009438 EnclosingContext = IMPDecl->getClassInterface();
9439 assert(EnclosingContext && "Implementation has no class interface!");
9440 }
9441 else
9442 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009443 } else {
9444 if (ObjCCategoryDecl *CDecl =
9445 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9446 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
9447 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00009448 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009449 }
9450 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00009451 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009452 }
Mike Stump11289f42009-09-09 15:08:12 +00009453
Ted Kremenek73295fa2008-07-23 18:04:17 +00009454 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009455 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9456 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00009457 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00009458
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009459 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009460 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00009461 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00009462 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009463 && !isa<TagDecl>(PrevDecl)) {
9464 Diag(Loc, diag::err_duplicate_member) << II;
9465 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9466 NewID->setInvalidDecl();
9467 }
9468 }
9469
Ted Kremenek73295fa2008-07-23 18:04:17 +00009470 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00009471 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00009472
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009473 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00009474 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00009475
John McCall31168b02011-06-15 23:02:42 +00009476 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009477 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +00009478 NewID->setInvalidDecl();
9479
Douglas Gregor3baa6702011-09-12 16:11:24 +00009480 if (D.getDeclSpec().isModulePrivateSpecified())
9481 NewID->setModulePrivate();
9482
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009483 if (II) {
9484 // FIXME: When interfaces are DeclContexts, we'll need to add
9485 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00009486 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009487 IdResolver.AddDecl(NewID);
9488 }
9489
John McCall48871652010-08-21 09:40:31 +00009490 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00009491}
9492
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009493/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9494/// class and class extensions. For every class @interface and class
9495/// extension @interface, if the last ivar is a bitfield of any type,
9496/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009497void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009498 SmallVectorImpl<Decl *> &AllIvarDecls) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009499 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9500 return;
9501
9502 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9503 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9504
Richard Smithcaf33902011-10-10 18:28:20 +00009505 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009506 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009507 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009508 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009509 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009510 if (!CD->IsClassExtension())
9511 return;
9512 }
9513 // No need to add this to end of @implementation.
9514 else
9515 return;
9516 }
9517 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +00009518 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9519 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009520
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009521 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009522 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009523 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +00009524 Context.getTrivialTypeSourceInfo(Context.CharTy,
9525 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009526 ObjCIvarDecl::Private, BW,
9527 true);
9528 AllIvarDecls.push_back(Ivar);
9529}
9530
Fariborz Jahanian343f7092007-09-29 00:54:24 +00009531void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00009532 SourceLocation RecLoc, Decl *EnclosingDecl,
David Blaikie751c5582011-09-22 02:58:26 +00009533 llvm::ArrayRef<Decl *> Fields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00009534 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00009535 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00009536 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00009537
Chris Lattnerd13b8b52009-02-23 22:00:08 +00009538 // If the decl this is being inserted into is invalid, then it may be a
9539 // redeclaration or some other bogus case. Don't try to add fields to it.
Douglas Gregor7bfedd62011-09-12 18:58:37 +00009540 if (EnclosingDecl->isInvalidDecl())
Chris Lattnerd13b8b52009-02-23 22:00:08 +00009541 return;
Mike Stump11289f42009-09-09 15:08:12 +00009542
Eli Friedmana7679412012-02-07 05:00:47 +00009543 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9544
9545 // Start counting up the number of named members; make sure to include
9546 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +00009547 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +00009548 if (Record) {
9549 for (RecordDecl::decl_iterator i = Record->decls_begin(),
9550 e = Record->decls_end(); i != e; i++) {
9551 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9552 if (IFD->getDeclName())
9553 ++NumNamedMembers;
9554 }
9555 }
9556
9557 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009558 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00009559
John McCall31168b02011-06-15 23:02:42 +00009560 bool ARCErrReported = false;
David Blaikie751c5582011-09-22 02:58:26 +00009561 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9562 i != end; ++i) {
9563 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +00009564
Chris Lattner720a0542007-01-25 00:44:24 +00009565 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00009566 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00009567
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009568 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00009569 // Remember all fields written by the user.
9570 RecFields.push_back(FD);
9571 }
Mike Stump11289f42009-09-09 15:08:12 +00009572
Chris Lattner73bf7b42009-03-05 22:45:59 +00009573 // If the field is already invalid for some reason, don't emit more
9574 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00009575 if (FD->isInvalidDecl()) {
9576 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00009577 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00009578 }
Mike Stump11289f42009-09-09 15:08:12 +00009579
Douglas Gregorac1fb652009-03-24 19:52:54 +00009580 // C99 6.7.2.1p2:
9581 // A structure or union shall not contain a member with
9582 // incomplete or function type (hence, a structure shall not
9583 // contain an instance of itself, but may contain a pointer to
9584 // an instance of itself), except that the last member of a
9585 // structure with more than one named member may have incomplete
9586 // array type; such a structure (and any union containing,
9587 // possibly recursively, a member that is such a structure)
9588 // shall not be a member of a structure or an element of an
9589 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00009590 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00009591 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00009592 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009593 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00009594 FD->setInvalidDecl();
9595 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00009596 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00009597 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +00009598 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00009599 ((getLangOpts().MicrosoftExt ||
9600 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +00009601 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00009602 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009603 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00009604 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00009605 // as the sole element of a struct/class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009606 if (getLangOpts().MicrosoftExt) {
Francois Pichetf657b632010-09-15 00:14:08 +00009607 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009608 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00009609 << FD->getDeclName();
David Blaikie751c5582011-09-22 02:58:26 +00009610 else if (Fields.size() == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009611 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00009612 << FD->getDeclName() << Record->getTagKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009613 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009614 if (Record->isUnion())
9615 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9616 << FD->getDeclName();
David Blaikie751c5582011-09-22 02:58:26 +00009617 else if (Fields.size() == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009618 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9619 << FD->getDeclName() << Record->getTagKind();
David Chisnall07518f22012-03-16 12:15:37 +00009620 } else if (!getLangOpts().C99) {
9621 if (Record->isUnion())
9622 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9623 << FD->getDeclName();
9624 else
9625 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
9626 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009627 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009628 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009629 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00009630 FD->setInvalidDecl();
9631 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00009632 continue;
9633 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009634 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +00009635 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009636 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00009637 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009638 FD->setInvalidDecl();
9639 EnclosingDecl->setInvalidDecl();
9640 continue;
9641 }
Chris Lattner720a0542007-01-25 00:44:24 +00009642 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00009643 if (Record)
9644 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00009645 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00009646 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00009647 diag::err_field_incomplete)) {
9648 // Incomplete type
9649 FD->setInvalidDecl();
9650 EnclosingDecl->setInvalidDecl();
9651 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009652 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00009653 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9654 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00009655 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00009656 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00009657 } else {
9658 // If this is a struct/class and this is not the last element, reject
9659 // it. Note that GCC supports variable sized arrays in the middle of
9660 // structures.
David Blaikie751c5582011-09-22 02:58:26 +00009661 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00009662 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00009663 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00009664 else {
9665 // We support flexible arrays at the end of structs in
9666 // other structs as an extension.
9667 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9668 << FD->getDeclName();
9669 if (Record)
9670 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00009671 }
Chris Lattner720a0542007-01-25 00:44:24 +00009672 }
9673 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00009674 if (Record && FDTTy->getDecl()->hasObjectMember())
9675 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00009676 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00009677 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009678 Diag(FD->getLocation(), diag::err_statically_allocated_object)
9679 << FixItHint::CreateInsertion(FD->getLocation(), "*");
9680 QualType T = Context.getObjCObjectPointerType(FD->getType());
9681 FD->setType(T);
John McCall31168b02011-06-15 23:02:42 +00009682 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00009683 else if (!getLangOpts().CPlusPlus) {
9684 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
John McCall31168b02011-06-15 23:02:42 +00009685 // It's an error in ARC if a field has lifetime.
9686 // We don't want to report this in a system header, though,
9687 // so we just make the field unavailable.
9688 // FIXME: that's really not sufficient; we need to make the type
9689 // itself invalid to, say, initialize or copy.
9690 QualType T = FD->getType();
9691 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9692 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9693 SourceLocation loc = FD->getLocation();
9694 if (getSourceManager().isInSystemHeader(loc)) {
9695 if (!FD->hasAttr<UnavailableAttr>()) {
9696 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009697 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00009698 }
9699 } else {
Fariborz Jahanianb989e6e2011-12-12 23:17:04 +00009700 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
9701 << T->isBlockPointerType();
John McCall31168b02011-06-15 23:02:42 +00009702 }
9703 ARCErrReported = true;
9704 }
9705 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00009706 else if (getLangOpts().ObjC1 &&
9707 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +00009708 Record && !Record->hasObjectMember()) {
9709 if (FD->getType()->isObjCObjectPointerType() ||
9710 FD->getType().isObjCGCStrong())
9711 Record->setHasObjectMember(true);
9712 else if (Context.getAsArrayType(FD->getType())) {
9713 QualType BaseType = Context.getBaseElementType(FD->getType());
9714 if (BaseType->isRecordType() &&
9715 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9716 Record->setHasObjectMember(true);
9717 else if (BaseType->isObjCObjectPointerType() ||
9718 BaseType.isObjCGCStrong())
9719 Record->setHasObjectMember(true);
9720 }
9721 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +00009722 }
Chris Lattner82625602007-01-24 02:26:21 +00009723 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009724 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00009725 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00009726 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009727
Chris Lattner82625602007-01-24 02:26:21 +00009728 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00009729 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00009730 bool Completed = false;
9731 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9732 if (!CXXRecord->isInvalidDecl()) {
9733 // Set access bits correctly on the directly-declared conversions.
9734 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9735 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9736 I != E; ++I)
9737 Convs->setAccess(I, (*I)->getAccess());
9738
9739 if (!CXXRecord->isDependentType()) {
John McCall31168b02011-06-15 23:02:42 +00009740 // Objective-C Automatic Reference Counting:
9741 // If a class has a non-static data member of Objective-C pointer
9742 // type (or array thereof), it is a non-POD type and its
9743 // default constructor (if any), copy constructor, copy assignment
9744 // operator, and destructor are non-trivial.
9745 //
9746 // This rule is also handled by CXXRecordDecl::completeDefinition().
9747 // However, here we check whether this particular class is only
9748 // non-POD because of the presence of an Objective-C pointer member.
9749 // If so, objects of this type cannot be shared between code compiled
9750 // with instant objects and code compiled with manual retain/release.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009751 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009752 CXXRecord->hasObjectMember() &&
9753 CXXRecord->getLinkage() == ExternalLinkage) {
9754 if (CXXRecord->isPOD()) {
9755 Diag(CXXRecord->getLocation(),
9756 diag::warn_arc_non_pod_class_with_object_member)
9757 << CXXRecord;
9758 } else {
9759 // FIXME: Fix-Its would be nice here, but finding a good location
9760 // for them is going to be tricky.
9761 if (CXXRecord->hasTrivialCopyConstructor())
9762 Diag(CXXRecord->getLocation(),
9763 diag::warn_arc_trivial_member_function_with_object_member)
9764 << CXXRecord << 0;
9765 if (CXXRecord->hasTrivialCopyAssignment())
9766 Diag(CXXRecord->getLocation(),
9767 diag::warn_arc_trivial_member_function_with_object_member)
9768 << CXXRecord << 1;
9769 if (CXXRecord->hasTrivialDestructor())
9770 Diag(CXXRecord->getLocation(),
9771 diag::warn_arc_trivial_member_function_with_object_member)
9772 << CXXRecord << 2;
9773 }
9774 }
9775
Sebastian Redl623ea822011-05-19 05:13:44 +00009776 // Adjust user-defined destructor exception spec.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009777 if (getLangOpts().CPlusPlus0x &&
Sebastian Redl623ea822011-05-19 05:13:44 +00009778 CXXRecord->hasUserDeclaredDestructor())
9779 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9780
Douglas Gregor8fb95122010-09-29 00:15:42 +00009781 // Add any implicitly-declared members to this class.
9782 AddImplicitlyDeclaredMembersToClass(CXXRecord);
9783
9784 // If we have virtual base classes, we may end up finding multiple
9785 // final overriders for a given virtual function. Check for this
9786 // problem now.
9787 if (CXXRecord->getNumVBases()) {
9788 CXXFinalOverriderMap FinalOverriders;
9789 CXXRecord->getFinalOverriders(FinalOverriders);
9790
9791 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
9792 MEnd = FinalOverriders.end();
9793 M != MEnd; ++M) {
9794 for (OverridingMethods::iterator SO = M->second.begin(),
9795 SOEnd = M->second.end();
9796 SO != SOEnd; ++SO) {
9797 assert(SO->second.size() > 0 &&
9798 "Virtual function without overridding functions?");
9799 if (SO->second.size() == 1)
9800 continue;
9801
9802 // C++ [class.virtual]p2:
9803 // In a derived class, if a virtual member function of a base
9804 // class subobject has more than one final overrider the
9805 // program is ill-formed.
9806 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9807 << (NamedDecl *)M->first << Record;
9808 Diag(M->first->getLocation(),
9809 diag::note_overridden_virtual_function);
9810 for (OverridingMethods::overriding_iterator
9811 OM = SO->second.begin(),
9812 OMEnd = SO->second.end();
9813 OM != OMEnd; ++OM)
9814 Diag(OM->Method->getLocation(), diag::note_final_overrider)
9815 << (NamedDecl *)M->first << OM->Method->getParent();
9816
9817 Record->setInvalidDecl();
9818 }
9819 }
9820 CXXRecord->completeDefinition(&FinalOverriders);
9821 Completed = true;
9822 }
9823 }
9824 }
9825 }
9826
9827 if (!Completed)
9828 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +00009829
Chris Lattner622c1932008-02-06 00:51:33 +00009830 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00009831 ObjCIvarDecl **ClsFields =
9832 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00009833 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +00009834 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00009835 // Add ivar's to class's DeclContext.
9836 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9837 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009838 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00009839 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00009840 // Must enforce the rule that ivars in the base classes may not be
9841 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00009842 if (ID->getSuperClass())
9843 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00009844 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00009845 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00009846 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00009847 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9848 // Ivar declared in @implementation never belongs to the implementation.
9849 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00009850 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00009851 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00009852 IMPDecl->setIvarLBraceLoc(LBrac);
9853 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00009854 } else if (ObjCCategoryDecl *CDecl =
9855 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009856 // case of ivars in class extension; all other cases have been
9857 // reported as errors elsewhere.
9858 // FIXME. Class extension does not have a LocEnd field.
9859 // CDecl->setLocEnd(RBrac);
9860 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +00009861 // Diagnose redeclaration of private ivars.
9862 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009863 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +00009864 if (IDecl) {
9865 if (const ObjCIvarDecl *ClsIvar =
9866 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9867 Diag(ClsFields[i]->getLocation(),
9868 diag::err_duplicate_ivar_declaration);
9869 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9870 continue;
9871 }
9872 for (const ObjCCategoryDecl *ClsExtDecl =
9873 IDecl->getFirstClassExtension();
9874 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9875 if (const ObjCIvarDecl *ClsExtIvar =
9876 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9877 Diag(ClsFields[i]->getLocation(),
9878 diag::err_duplicate_ivar_declaration);
9879 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9880 continue;
9881 }
9882 }
9883 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009884 ClsFields[i]->setLexicalDeclContext(CDecl);
9885 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00009886 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00009887 CDecl->setIvarLBraceLoc(LBrac);
9888 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00009889 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00009890 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00009891
9892 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00009893 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00009894
9895 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9896 // set the visibility of this record.
9897 if (Record && !Record->getDeclContext()->isRecord())
9898 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00009899}
9900
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009901/// \brief Determine whether the given integral value is representable within
9902/// the given type T.
9903static bool isRepresentableIntegerValue(ASTContext &Context,
9904 llvm::APSInt &Value,
9905 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00009906 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00009907 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009908
Douglas Gregor0bf31402010-10-08 23:50:27 +00009909 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009910 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +00009911 --BitWidth;
9912 return Value.getActiveBits() <= BitWidth;
9913 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009914 return Value.getMinSignedBits() <= BitWidth;
9915}
9916
9917// \brief Given an integral type, return the next larger integral type
9918// (or a NULL type of no such type exists).
9919static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9920 // FIXME: Int128/UInt128 support, which also needs to be introduced into
9921 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00009922 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009923 const unsigned NumTypes = 4;
9924 QualType SignedIntegralTypes[NumTypes] = {
9925 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9926 };
9927 QualType UnsignedIntegralTypes[NumTypes] = {
9928 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
9929 Context.UnsignedLongLongTy
9930 };
9931
9932 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009933 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9934 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009935 for (unsigned I = 0; I != NumTypes; ++I)
9936 if (Context.getTypeSize(Types[I]) > BitWidth)
9937 return Types[I];
9938
9939 return QualType();
9940}
9941
Douglas Gregor954f6b272009-03-17 19:05:46 +00009942EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9943 EnumConstantDecl *LastEnumConst,
9944 SourceLocation IdLoc,
9945 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00009946 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00009947 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009948 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00009949 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00009950
9951 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9952 Val = 0;
9953
Eli Friedman7c6515a2011-12-06 00:10:34 +00009954 if (Val)
9955 Val = DefaultLvalueConversion(Val).take();
9956
Douglas Gregorb2186fe2009-11-06 00:03:12 +00009957 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00009958 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00009959 EltTy = Context.DependentTy;
9960 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00009961 SourceLocation ExpLoc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009962 if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
9963 !getLangOpts().MicrosoftMode) {
Richard Smithf8379a02012-01-18 23:55:52 +00009964 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
9965 // constant-expression in the enumerator-definition shall be a converted
9966 // constant expression of the underlying type.
9967 EltTy = Enum->getIntegerType();
9968 ExprResult Converted =
9969 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
9970 CCEK_Enumerator);
9971 if (Converted.isInvalid())
9972 Val = 0;
9973 else
9974 Val = Converted.take();
9975 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +00009976 !(Val = VerifyIntegerConstantExpression(Val,
9977 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +00009978 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +00009979 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +00009980 if (Enum->isFixed()) {
9981 EltTy = Enum->getIntegerType();
9982
Richard Smithf8379a02012-01-18 23:55:52 +00009983 // In Obj-C and Microsoft mode, require the enumeration value to be
9984 // representable in the underlying type of the enumeration. In C++11,
9985 // we perform a non-narrowing conversion as part of converted constant
9986 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +00009987 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009988 if (getLangOpts().MicrosoftMode) {
Francois Picheta3108062010-10-18 15:01:13 +00009989 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +00009990 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +00009991 } else
9992 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +00009993 } else
John Wiegley01296292011-04-08 18:41:53 +00009994 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009995 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +00009996 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +00009997 // If the underlying type is not fixed, the type of each enumerator
9998 // is the type of its initializing value:
9999 // - If an initializer is specified for an enumerator, the
10000 // initializing value has the same type as the expression.
10001 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000010002 } else {
10003 // C99 6.7.2.2p2:
10004 // The expression that defines the value of an enumeration constant
10005 // shall be an integer constant expression that has a value
10006 // representable as an int.
10007
10008 // Complain if the value is not representable in an int.
10009 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10010 Diag(IdLoc, diag::ext_enum_value_not_int)
10011 << EnumVal.toString(10) << Val->getSourceRange()
10012 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10013 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10014 // Force the type of the expression to 'int'.
10015 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10016 }
10017 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010018 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010019 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000010020 }
10021 }
Mike Stump11289f42009-09-09 15:08:12 +000010022
Douglas Gregor954f6b272009-03-17 19:05:46 +000010023 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000010024 if (Enum->isDependentType())
10025 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010026 else if (!LastEnumConst) {
10027 // C++0x [dcl.enum]p5:
10028 // If the underlying type is not fixed, the type of each enumerator
10029 // is the type of its initializing value:
10030 // - If no initializer is specified for the first enumerator, the
10031 // initializing value has an unspecified integral type.
10032 //
10033 // GCC uses 'int' for its unspecified integral type, as does
10034 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000010035 if (Enum->isFixed()) {
10036 EltTy = Enum->getIntegerType();
10037 }
10038 else {
10039 EltTy = Context.IntTy;
10040 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010041 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000010042 // Assign the last value + 1.
10043 EnumVal = LastEnumConst->getInitVal();
10044 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010045 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000010046
10047 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010048 if (EnumVal < LastEnumConst->getInitVal()) {
10049 // C++0x [dcl.enum]p5:
10050 // If the underlying type is not fixed, the type of each enumerator
10051 // is the type of its initializing value:
10052 //
10053 // - Otherwise the type of the initializing value is the same as
10054 // the type of the initializing value of the preceding enumerator
10055 // unless the incremented value is not representable in that type,
10056 // in which case the type is an unspecified integral type
10057 // sufficient to contain the incremented value. If no such type
10058 // exists, the program is ill-formed.
10059 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010060 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010061 // There is no integral type larger enough to represent this
10062 // value. Complain, then allow the value to wrap around.
10063 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000010064 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010065 ++EnumVal;
10066 if (Enum->isFixed())
10067 // When the underlying type is fixed, this is ill-formed.
10068 Diag(IdLoc, diag::err_enumerator_wrapped)
10069 << EnumVal.toString(10)
10070 << EltTy;
10071 else
10072 Diag(IdLoc, diag::warn_enumerator_too_large)
10073 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010074 } else {
10075 EltTy = T;
10076 }
10077
10078 // Retrieve the last enumerator's value, extent that type to the
10079 // type that is supposed to be large enough to represent the incremented
10080 // value, then increment.
10081 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010082 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000010083 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010084 ++EnumVal;
10085
10086 // If we're not in C++, diagnose the overflow of enumerator values,
10087 // which in C99 means that the enumerator value is not representable in
10088 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10089 // permits enumerator values that are representable in some larger
10090 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010091 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010092 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010093 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010094 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10095 // Enforce C99 6.7.2.2p2 even when we compute the next value.
10096 Diag(IdLoc, diag::ext_enum_value_not_int)
10097 << EnumVal.toString(10) << 1;
10098 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000010099 }
10100 }
Mike Stump11289f42009-09-09 15:08:12 +000010101
Douglas Gregordc70c3a2010-03-02 17:53:14 +000010102 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010103 // Make the enumerator value match the signedness and size of the
10104 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000010105 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010106 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010107 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010108
Douglas Gregor954f6b272009-03-17 19:05:46 +000010109 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000010110 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000010111}
10112
10113
John McCall811a0f52010-10-22 23:36:17 +000010114Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10115 SourceLocation IdLoc, IdentifierInfo *Id,
10116 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000010117 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000010118 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000010119 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000010120 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000010121
Chris Lattner1a76a3c2007-08-26 06:24:45 +000010122 // The scope passed in may not be a decl scope. Zip up the scope tree until
10123 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000010124 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000010125
Chris Lattner8116d1b2007-01-25 22:38:29 +000010126 // Verify that there isn't already something declared with this name in this
10127 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010128 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000010129 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000010130 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010131 // Maybe we will complain about the shadowed template parameter.
10132 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10133 // Just pretend that we didn't see the previous declaration.
10134 PrevDecl = 0;
10135 }
10136
10137 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000010138 // When in C++, we may get a TagDecl with the same name; in this case the
10139 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010140 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000010141 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000010142 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000010143 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010144 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000010145 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010146 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000010147 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000010148 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000010149 }
10150 }
Chris Lattner4ef40012007-06-11 01:28:17 +000010151
Douglas Gregor36c22a22010-10-15 13:21:21 +000010152 // C++ [class.mem]p13:
10153 // If T is the name of a class, then each of the following shall have a
10154 // name different from T:
10155 // - every enumerator of every member of class T that is an enumerated
10156 // type
10157 if (CXXRecordDecl *Record
10158 = dyn_cast<CXXRecordDecl>(
10159 TheEnumDecl->getDeclContext()->getRedeclContext()))
10160 if (Record->getIdentifier() && Record->getIdentifier() == Id)
10161 Diag(IdLoc, diag::err_member_name_of_class) << Id;
10162
John McCall811a0f52010-10-22 23:36:17 +000010163 EnumConstantDecl *New =
10164 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000010165
John McCall553c0792010-01-23 00:46:32 +000010166 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000010167 // Process attributes.
10168 if (Attr) ProcessDeclAttributeList(S, New, Attr);
10169
10170 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000010171 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000010172 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000010173 }
Douglas Gregor2f521192008-12-17 02:04:30 +000010174
John McCall48871652010-08-21 09:40:31 +000010175 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000010176}
10177
Mike Stump6814d1c2009-05-16 07:06:02 +000010178void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000010179 SourceLocation RBraceLoc, Decl *EnumDeclX,
10180 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010181 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000010182 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000010183 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010184
10185 if (Attr)
10186 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000010187
Eli Friedmand0e60972009-12-11 01:34:50 +000010188 if (Enum->isDependentType()) {
10189 for (unsigned i = 0; i != NumElements; ++i) {
10190 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000010191 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000010192 if (!ECD) continue;
10193
10194 ECD->setType(EnumType);
10195 }
10196
John McCall9aa35be2010-05-06 08:49:23 +000010197 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000010198 return;
10199 }
10200
Chris Lattner67933c02007-08-28 05:10:31 +000010201 // TODO: If the result value doesn't fit in an int, it must be a long or long
10202 // long value. ISO C does not support this, but GCC does as an extension,
10203 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000010204 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10205 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10206 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010207
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010208 // Verify that all the values are okay, compute the size of the values, and
10209 // reverse the list.
10210 unsigned NumNegativeBits = 0;
10211 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000010212
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010213 // Keep track of whether all elements have type int.
10214 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000010215
Chris Lattnerc1915e22007-01-25 07:29:02 +000010216 for (unsigned i = 0; i != NumElements; ++i) {
10217 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000010218 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000010219 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000010220
Chris Lattnerbf478cb2007-08-28 05:27:00 +000010221 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000010222
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010223 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000010224 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000010225 NumPositiveBits = std::max(NumPositiveBits,
10226 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010227 else
Chris Lattner49f980c2008-01-14 21:47:29 +000010228 NumNegativeBits = std::max(NumNegativeBits,
10229 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000010230
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010231 // Keep track of whether every enum element has type int (very commmon).
10232 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000010233 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000010234 }
Mike Stump11289f42009-09-09 15:08:12 +000010235
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010236 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010237 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010238 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010239
John McCall56774992009-12-09 09:09:27 +000010240 // C++0x N3000 [conv.prom]p3:
10241 // An rvalue of an unscoped enumeration type whose underlying
10242 // type is not fixed can be converted to an rvalue of the first
10243 // of the following types that can represent all the values of
10244 // the enumeration: int, unsigned int, long int, unsigned long
10245 // int, long long int, or unsigned long long int.
10246 // C99 6.4.4.3p2:
10247 // An identifier declared as an enumeration constant has type int.
10248 // The C99 rule is modified by a gcc extension
10249 QualType BestPromotionType;
10250
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010251 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000010252 // -fshort-enums is the equivalent to specifying the packed attribute on all
10253 // enum definitions.
10254 if (LangOpts.ShortEnums)
10255 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010256
Douglas Gregor0bf31402010-10-08 23:50:27 +000010257 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000010258 BestType = Enum->getIntegerType();
10259 if (BestType->isPromotableIntegerType())
10260 BestPromotionType = Context.getPromotedIntegerType(BestType);
10261 else
10262 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000010263 // We don't need to set BestWidth, because BestType is going to be the type
10264 // of the enumerators, but we do anyway because otherwise some compilers
10265 // warn that it might be used uninitialized.
10266 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010267 }
10268 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000010269 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010270 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010271 // If it's packed, check also if it fits a char or a short.
10272 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000010273 BestType = Context.SignedCharTy;
10274 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000010275 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010276 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000010277 BestType = Context.ShortTy;
10278 BestWidth = ShortWidth;
10279 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010280 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010281 BestWidth = IntWidth;
10282 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010283 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010284
John McCall56774992009-12-09 09:09:27 +000010285 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010286 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000010287 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010288 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010289
Chris Lattner3a370bf2007-08-29 17:31:48 +000010290 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010291 Diag(Enum->getLocation(), diag::warn_enum_too_large);
10292 BestType = Context.LongLongTy;
10293 }
10294 }
John McCall56774992009-12-09 09:09:27 +000010295 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010296 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000010297 // If there is no negative value, figure out the smallest type that fits
10298 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010299 // If it's packed, check also if it fits a char or a short.
10300 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000010301 BestType = Context.UnsignedCharTy;
10302 BestPromotionType = Context.IntTy;
10303 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010304 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000010305 BestType = Context.UnsignedShortTy;
10306 BestPromotionType = Context.IntTy;
10307 BestWidth = ShortWidth;
10308 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010309 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010310 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000010311 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010312 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010313 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010314 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000010315 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010316 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000010317 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010318 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010319 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000010320 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010321 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010322 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010323 "How could an initializer get larger than ULL?");
10324 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000010325 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010326 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010327 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010328 }
10329 }
Mike Stump11289f42009-09-09 15:08:12 +000010330
Chris Lattner3a370bf2007-08-29 17:31:48 +000010331 // Loop over all of the enumerator constants, changing their types to match
10332 // the type of the enum if needed.
10333 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +000010334 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010335 if (!ECD) continue; // Already issued a diagnostic.
10336
10337 // Standard C says the enumerators have int type, but we allow, as an
10338 // extension, the enumerators to be larger than int size. If each
10339 // enumerator value fits in an int, type it as an int, otherwise type it the
10340 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
10341 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000010342
10343 // Determine whether the value fits into an int.
10344 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010345
10346 // If it fits into an integer type, force it. Otherwise force it to match
10347 // the enum decl type.
10348 QualType NewTy;
10349 unsigned NewWidth;
10350 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010351 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000010352 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010353 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000010354 NewTy = Context.IntTy;
10355 NewWidth = IntWidth;
10356 NewSign = true;
10357 } else if (ECD->getType() == BestType) {
10358 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000010359 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000010360 // C++ [dcl.enum]p4: Following the closing brace of an
10361 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000010362 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000010363 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010364 continue;
10365 } else {
10366 NewTy = BestType;
10367 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010368 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010369 }
10370
10371 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010372 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010373 InitVal.setIsSigned(NewSign);
10374 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000010375
Chris Lattner3a370bf2007-08-29 17:31:48 +000010376 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000010377 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000010378 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000010379 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000010380 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000010381 ECD->getInitExpr(),
10382 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000010383 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000010384 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000010385 // C++ [dcl.enum]p4: Following the closing brace of an
10386 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000010387 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000010388 ECD->setType(EnumType);
10389 else
10390 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010391 }
Mike Stump11289f42009-09-09 15:08:12 +000010392
John McCall9aa35be2010-05-06 08:49:23 +000010393 Enum->completeDefinition(BestType, BestPromotionType,
10394 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000010395
10396 // If we're declaring a function, ensure this decl isn't forgotten about -
10397 // it needs to go into the function scope.
10398 if (InFunctionDeclarator)
10399 DeclsInPrototypeScope.push_back(Enum);
10400
Chris Lattnerc1915e22007-01-25 07:29:02 +000010401}
Chris Lattner1300fb92007-01-23 23:42:53 +000010402
Abramo Bagnara348823a2011-03-03 14:20:18 +000010403Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10404 SourceLocation StartLoc,
10405 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000010406 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000010407
Douglas Gregor278f52e2009-05-30 00:08:05 +000010408 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000010409 AsmString, StartLoc,
10410 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010411 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000010412 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000010413}
Eli Friedman5ed51982009-06-05 02:44:36 +000010414
Douglas Gregor22d09742012-01-03 18:04:46 +000010415DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10416 SourceLocation ImportLoc,
10417 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000010418 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000010419 Module::AllVisible,
10420 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000010421 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000010422 return true;
10423
Douglas Gregorba345522011-12-02 23:23:56 +000010424 llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10425 Module *ModCheck = Mod;
10426 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10427 // If we've run out of module parents, just drop the remaining identifiers.
10428 // We need the length to be consistent.
10429 if (!ModCheck)
10430 break;
10431 ModCheck = ModCheck->Parent;
10432
10433 IdentifierLocs.push_back(Path[I].second);
10434 }
10435
10436 ImportDecl *Import = ImportDecl::Create(Context,
10437 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000010438 AtLoc.isValid()? AtLoc : ImportLoc,
10439 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000010440 Context.getTranslationUnitDecl()->addDecl(Import);
10441 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000010442}
10443
David Chisnall0867d9c2012-02-18 16:12:34 +000010444void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10445 IdentifierInfo* AliasName,
10446 SourceLocation PragmaLoc,
10447 SourceLocation NameLoc,
10448 SourceLocation AliasNameLoc) {
10449 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10450 LookupOrdinaryName);
10451 AsmLabelAttr *Attr =
10452 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall0867d9c2012-02-18 16:12:34 +000010453
10454 if (PrevDecl)
10455 PrevDecl->addAttr(Attr);
10456 else
10457 (void)ExtnameUndeclaredIdentifiers.insert(
10458 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10459}
10460
Eli Friedman5ed51982009-06-05 02:44:36 +000010461void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10462 SourceLocation PragmaLoc,
10463 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010464 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000010465
Eli Friedman5ed51982009-06-05 02:44:36 +000010466 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010467 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +000010468 } else {
10469 (void)WeakUndeclaredIdentifiers.insert(
10470 std::pair<IdentifierInfo*,WeakInfo>
10471 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000010472 }
Eli Friedman5ed51982009-06-05 02:44:36 +000010473}
10474
10475void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10476 IdentifierInfo* AliasName,
10477 SourceLocation PragmaLoc,
10478 SourceLocation NameLoc,
10479 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010480 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10481 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000010482 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000010483
Eli Friedman5ed51982009-06-05 02:44:36 +000010484 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000010485 if (!PrevDecl->hasAttr<AliasAttr>())
10486 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000010487 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000010488 } else {
10489 (void)WeakUndeclaredIdentifiers.insert(
10490 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000010491 }
Eli Friedman5ed51982009-06-05 02:44:36 +000010492}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010493
10494Decl *Sema::getObjCDeclContext() const {
10495 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10496}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000010497
10498AvailabilityResult Sema::getCurContextAvailability() const {
10499 const Decl *D = cast<Decl>(getCurLexicalContext());
10500 // A category implicitly has the availability of the interface.
10501 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10502 D = CatD->getClassInterface();
10503
10504 return D->getAvailability();
10505}