blob: 001a6ac61d2b329d089e92fbab77578d6f635996 [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"
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000024#include "clang/AST/CommentDiagnostic.h"
John McCall28a0cf72010-08-25 07:42:41 +000025#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000027#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000029#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000030#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000031#include "clang/AST/CharUnits.h"
John McCall8b0666c2010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000034#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Fariborz Jahanianed1933b2011-10-03 22:11:57 +000036#include "clang/Sema/DelayedDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000037#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000038#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000039// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000040#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000041#include "clang/Lex/HeaderSearch.h"
Douglas Gregor08142532011-08-26 23:56:07 +000042#include "clang/Lex/ModuleLoader.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000043#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000044#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000045#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000046#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000047#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000048using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000049using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000050
Richard Smithcd1c0552011-07-01 19:46:12 +000051Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
52 if (OwnedType) {
53 Decl *Group[2] = { OwnedType, Ptr };
54 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
55 }
56
John McCall48871652010-08-21 09:40:31 +000057 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000058}
59
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000060namespace {
61
62class TypeNameValidatorCCC : public CorrectionCandidateCallback {
63 public:
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000064 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
65 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000066 WantExpressionKeywords = false;
67 WantCXXNamedCasts = false;
68 WantRemainingKeywords = false;
69 }
70
71 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
72 if (NamedDecl *ND = candidate.getCorrectionDecl())
73 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
74 (AllowInvalidDecl || !ND->isInvalidDecl());
75 else
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000076 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000077 }
78
79 private:
80 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000081 bool WantClassName;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000082};
83
84}
85
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +000086/// \brief Determine whether the token kind starts a simple-type-specifier.
87bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
88 switch (Kind) {
89 // FIXME: Take into account the current language when deciding whether a
90 // token kind is a valid type specifier
91 case tok::kw_short:
92 case tok::kw_long:
93 case tok::kw___int64:
94 case tok::kw___int128:
95 case tok::kw_signed:
96 case tok::kw_unsigned:
97 case tok::kw_void:
98 case tok::kw_char:
99 case tok::kw_int:
100 case tok::kw_half:
101 case tok::kw_float:
102 case tok::kw_double:
103 case tok::kw_wchar_t:
104 case tok::kw_bool:
105 case tok::kw___underlying_type:
106 return true;
107
108 case tok::annot_typename:
109 case tok::kw_char16_t:
110 case tok::kw_char32_t:
111 case tok::kw_typeof:
112 case tok::kw_decltype:
113 return getLangOpts().CPlusPlus;
114
115 default:
116 break;
117 }
118
119 return false;
120}
121
Douglas Gregorec6e1892009-02-04 19:16:12 +0000122/// \brief If the identifier refers to a type name within this scope,
123/// return the declaration of that type.
124///
125/// This routine performs ordinary name lookup of the identifier II
126/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000127/// determine whether the name refers to a type. If so, returns an
128/// opaque pointer (actually a QualType) corresponding to that
129/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +0000130///
131/// If name lookup results in an ambiguity, this routine will complain
132/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +0000133ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
134 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000135 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000136 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000137 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000138 bool WantNontrivialTypeSourceInfo,
139 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000140 // Determine where we will perform name lookup.
141 DeclContext *LookupCtx = 0;
142 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000143 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000144 if (ObjectType->isRecordType())
145 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000146 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000147 LookupCtx = computeDeclContext(*SS, false);
148
149 if (!LookupCtx) {
150 if (isDependentScopeSpecifier(*SS)) {
151 // C++ [temp.res]p3:
152 // A qualified-id that refers to a type and in which the
153 // nested-name-specifier depends on a template-parameter (14.6.2)
154 // shall be prefixed by the keyword typename to indicate that the
155 // qualified-id denotes a type, forming an
156 // elaborated-type-specifier (7.1.5.3).
157 //
158 // We therefore do not perform any name lookup if the result would
159 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000160 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000162
John McCallc392f372010-06-11 00:33:02 +0000163 // We know from the grammar that this name refers to a type,
164 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000165 if (WantNontrivialTypeSourceInfo)
166 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
167
168 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000169 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000170 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000171 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000172
173 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000174 }
175
John McCallba7bf592010-08-24 05:47:05 +0000176 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000177 }
178
John McCall0b66eb32010-05-01 00:40:08 +0000179 if (!LookupCtx->isDependentContext() &&
180 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000181 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000182 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000183
184 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
185 // lookup for class-names.
186 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
187 LookupOrdinaryName;
188 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000189 if (LookupCtx) {
190 // Perform "qualified" name lookup into the declaration context we
191 // computed, which is either the type of the base of a member access
192 // expression or the declaration context associated with a prior
193 // nested-name-specifier.
194 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000195
Douglas Gregora25d65d2009-11-20 22:03:38 +0000196 if (ObjectTypePtr && Result.empty()) {
197 // C++ [basic.lookup.classref]p3:
198 // If the unqualified-id is ~type-name, the type-name is looked up
199 // in the context of the entire postfix-expression. If the type T of
200 // the object expression is of a class type C, the type-name is also
201 // looked up in the scope of class C. At least one of the lookups shall
202 // find a name that refers to (possibly cv-qualified) T.
203 LookupName(Result, S);
204 }
205 } else {
206 // Perform unqualified name lookup.
207 LookupName(Result, S);
208 }
209
Chris Lattnera3778332009-02-16 22:07:16 +0000210 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000211 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000212 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000213 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000214 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000215 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000216 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000217 Kind, S, SS, Validator);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000218 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
219 TemplateTy Template;
220 bool MemberOfUnknownSpecialization;
221 UnqualifiedId TemplateName;
222 TemplateName.setIdentifier(NewII, NameLoc);
223 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
224 CXXScopeSpec NewSS, *NewSSPtr = SS;
225 if (SS && NNS) {
226 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
227 NewSSPtr = &NewSS;
228 }
229 if (Correction && (NNS || NewII != &II) &&
230 // Ignore a correction to a template type as the to-be-corrected
231 // identifier is not a template (typo correction for template names
232 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000233 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000234 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
235 false, Template, MemberOfUnknownSpecialization))) {
236 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
237 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000238 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000239 WantNontrivialTypeSourceInfo);
240 if (Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000241 std::string CorrectedStr(Correction.getAsString(getLangOpts()));
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000242 std::string CorrectedQuotedStr(
David Blaikiebbafb8a2012-03-11 07:00:24 +0000243 Correction.getQuoted(getLangOpts()));
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000244 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
245 << Result.getLookupName() << CorrectedQuotedStr << isClassName
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000246 << FixItHint::CreateReplacement(SourceRange(NameLoc),
247 CorrectedStr);
248 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
249 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
250 << CorrectedQuotedStr;
251
252 if (SS && NNS)
253 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
254 *CorrectedII = NewII;
255 return Ty;
256 }
257 }
258 }
259 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000260 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000261 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000262 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000263 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000264
Chris Lattnere40853a2009-10-25 22:09:09 +0000265 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000266 // Recover from type-hiding ambiguities by hiding the type. We'll
267 // do the lookup again when looking for an object, and we can
268 // diagnose the error then. If we don't do this, then the error
269 // about hiding the type will be immediately followed by an error
270 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000271 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
272 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000273 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000274 }
John McCall6538c932009-10-10 05:48:19 +0000275
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000276 // Look to see if we have a type anywhere in the list of results.
277 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
278 Res != ResEnd; ++Res) {
279 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000280 if (!IIDecl ||
281 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000282 IIDecl->getLocation().getRawEncoding())
283 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000284 }
285 }
286
287 if (!IIDecl) {
288 // None of the entities we found is a type, so there is no way
289 // to even assume that the result is a type. In this case, don't
290 // complain about the ambiguity. The parser will either try to
291 // perform this lookup again (e.g., as an object name), which
292 // will produce the ambiguity, or will complain that it expected
293 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000294 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000295 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000296 }
297
298 // We found a type within the ambiguous lookup; diagnose the
299 // ambiguity and then return that type. This might be the right
300 // answer, or it might not be, but it suppresses any attempt to
301 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000302 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000303
Chris Lattnera3778332009-02-16 22:07:16 +0000304 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000305 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000306 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000307 }
308
Chris Lattner17e15f12009-10-25 17:16:46 +0000309 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000310
Chris Lattner17e15f12009-10-25 17:16:46 +0000311 QualType T;
312 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000313 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000314
Chris Lattner17e15f12009-10-25 17:16:46 +0000315 if (T.isNull())
316 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-01-27 08:46:19 +0000317
318 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
319 // constructor or destructor name (in such a case, the scope specifier
320 // will be attached to the enclosing Expr or Decl node).
321 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor844cb502011-03-01 18:12:44 +0000322 if (WantNontrivialTypeSourceInfo) {
323 // Construct a type with type-source information.
324 TypeLocBuilder Builder;
325 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
326
327 T = getElaboratedType(ETK_None, *SS, T);
328 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000329 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-03-01 18:12:44 +0000330 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
331 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
332 } else {
333 T = getElaboratedType(ETK_None, *SS, T);
334 }
335 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000336 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000337 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000338 if (!HasTrailingDot)
339 T = Context.getObjCInterfaceType(IDecl);
340 }
341
342 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000343 // If it's not plausibly a type, suppress diagnostics.
344 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000345 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000346 }
John McCallba7bf592010-08-24 05:47:05 +0000347 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000348}
349
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000350/// isTagName() - This method is called *for error recovery purposes only*
351/// to determine if the specified name is a valid tag name ("struct foo"). If
352/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matosdc86f942012-08-31 18:45:21 +0000353/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
354/// cases in C where the user forgot to specify the tag.
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000355DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
356 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000357 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
358 LookupName(R, S, false);
359 R.suppressDiagnostics();
360 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000361 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000362 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000363 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000364 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-05-11 21:36:43 +0000365 case TTK_Union: return DeclSpec::TST_union;
366 case TTK_Class: return DeclSpec::TST_class;
367 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000368 }
369 }
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000371 return DeclSpec::TST_unspecified;
372}
373
Francois Pichet48c946e2011-04-13 02:38:49 +0000374/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
375/// if a CXXScopeSpec's type is equal to the type of one of the base classes
376/// then downgrade the missing typename error to a warning.
377/// This is needed for MSVC compatibility; Example:
378/// @code
379/// template<class T> class A {
380/// public:
381/// typedef int TYPE;
382/// };
383/// template<class T> class B : public A<T> {
384/// public:
385/// A<T>::TYPE a; // no typename required because A<T> is a base class.
386/// };
387/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000388bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000389 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000390 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000391
392 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
393 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
394 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
395 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
396 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000397 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000398 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000399 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000400}
401
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000402bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000403 SourceLocation IILoc,
404 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000405 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000406 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000407 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000408 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000409
Douglas Gregor2d435302009-12-30 17:04:44 +0000410 // There may have been a typo in the name of the type. Look up typo
411 // results, in case we have something that we can suggest.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000412 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000413 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000414 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000415 Validator)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000416 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
417 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000418
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000419 if (Corrected.isKeyword()) {
420 // We corrected to a keyword.
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000421 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
422 if (!isSimpleTypeSpecifier(NewII->getTokenID()))
423 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000424 Diag(IILoc, diag::err_unknown_typename_suggest)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000425 << II << CorrectedQuotedStr
426 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
427 II = NewII;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000428 } else {
429 NamedDecl *Result = Corrected.getCorrectionDecl();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000430 // We found a similarly-named type or interface; suggest that.
431 if (!SS || !SS->isSet())
432 Diag(IILoc, diag::err_unknown_typename_suggest)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000433 << II << CorrectedQuotedStr
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000434 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
435 else if (DeclContext *DC = computeDeclContext(*SS, false))
436 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000437 << II << DC << CorrectedQuotedStr << SS->getRange()
David Blaikie04ea41c2012-10-12 20:00:44 +0000438 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
439 CorrectedStr);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000440 else
441 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000442
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000443 Diag(Result->getLocation(), diag::note_previous_decl)
444 << CorrectedQuotedStr;
445
446 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
447 false, false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000448 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000449 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000450 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000451 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000452 }
453
David Blaikiebbafb8a2012-03-11 07:00:24 +0000454 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000455 // See if II is a class template that the user forgot to pass arguments to.
456 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000457 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000458 CXXScopeSpec EmptySS;
459 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000460 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000461 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000462 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000463 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000464 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
465 Diag(IILoc, diag::err_template_missing_args) << TplName;
466 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
467 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
468 << TplDecl->getTemplateParameters()->getSourceRange();
469 }
470 return true;
471 }
472 }
473
Douglas Gregor15e56022009-10-13 23:27:22 +0000474 // FIXME: Should we move the logic that tries to recover from a missing tag
475 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
476
Douglas Gregor2d435302009-12-30 17:04:44 +0000477 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000478 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000479 else if (DeclContext *DC = computeDeclContext(*SS, false))
480 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000481 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000482 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000483 unsigned DiagID = diag::err_typename_missing;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000484 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000485 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000486
487 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000488 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000489 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000490 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000491 SuggestedType = ActOnTypenameType(S, SourceLocation(),
492 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000493 } else {
494 assert(SS && SS->isInvalid() &&
495 "Invalid scope specifier has already been diagnosed");
496 }
497
498 return true;
499}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000500
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000501/// \brief Determine whether the given result set contains either a type name
502/// or
503static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000505 NextToken.is(tok::less);
506
507 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
508 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
509 return true;
510
511 if (CheckTemplate && isa<TemplateDecl>(*I))
512 return true;
513 }
514
515 return false;
516}
517
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000518static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
519 Scope *S, CXXScopeSpec &SS,
520 IdentifierInfo *&Name,
521 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000522 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
523 SemaRef.LookupParsedName(R, S, &SS);
524 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000525 const char *TagName = 0;
526 const char *FixItTagName = 0;
527 switch (Tag->getTagKind()) {
528 case TTK_Class:
529 TagName = "class";
530 FixItTagName = "class ";
531 break;
532
533 case TTK_Enum:
534 TagName = "enum";
535 FixItTagName = "enum ";
536 break;
537
538 case TTK_Struct:
539 TagName = "struct";
540 FixItTagName = "struct ";
541 break;
542
Joao Matosdc86f942012-08-31 18:45:21 +0000543 case TTK_Interface:
544 TagName = "__interface";
545 FixItTagName = "__interface ";
546 break;
547
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000548 case TTK_Union:
549 TagName = "union";
550 FixItTagName = "union ";
551 break;
552 }
553
554 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
555 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
556 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
557
Richard Smithaa31b4b2012-09-06 01:37:56 +0000558 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
559 I != IEnd; ++I)
560 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
561 << Name << TagName;
562
563 // Replace lookup results with just the tag decl.
564 Result.clear(Sema::LookupTagName);
565 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000566 return true;
567 }
568
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000569 return false;
570}
571
Richard Smith4f605af2012-08-18 00:55:03 +0000572/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
573static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
574 QualType T, SourceLocation NameLoc) {
575 ASTContext &Context = S.Context;
576
577 TypeLocBuilder Builder;
578 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
579
580 T = S.getElaboratedType(ETK_None, SS, T);
581 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
582 ElabTL.setElaboratedKeywordLoc(SourceLocation());
583 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
584 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
585}
586
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000587Sema::NameClassification Sema::ClassifyName(Scope *S,
588 CXXScopeSpec &SS,
589 IdentifierInfo *&Name,
590 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000591 const Token &NextToken,
592 bool IsAddressOfOperand,
593 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000594 DeclarationNameInfo NameInfo(Name, NameLoc);
595 ObjCMethodDecl *CurMethod = getCurMethodDecl();
596
597 if (NextToken.is(tok::coloncolon)) {
598 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
599 QualType(), false, SS, 0, false);
600
601 }
602
603 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
604 LookupParsedName(Result, S, &SS, !CurMethod);
605
606 // Perform lookup for Objective-C instance variables (including automatically
607 // synthesized instance variables), if we're in an Objective-C method.
608 // FIXME: This lookup really, really needs to be folded in to the normal
609 // unqualified lookup mechanism.
610 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
611 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000612 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000613 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000614 }
615
616 bool SecondTry = false;
617 bool IsFilteredTemplateName = false;
618
619Corrected:
620 switch (Result.getResultKind()) {
621 case LookupResult::NotFound:
622 // If an unqualified-id is followed by a '(', then we have a function
623 // call.
624 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
625 // In C++, this is an ADL-only call.
626 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000627 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000628 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
629
630 // C90 6.3.2.2:
631 // If the expression that precedes the parenthesized argument list in a
632 // function call consists solely of an identifier, and if no
633 // declaration is visible for this identifier, the identifier is
634 // implicitly declared exactly as if, in the innermost block containing
635 // the function call, the declaration
636 //
637 // extern int identifier ();
638 //
639 // appeared.
640 //
641 // We also allow this in C99 as an extension.
642 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
643 Result.addDecl(D);
644 Result.resolveKind();
645 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
646 }
647 }
648
649 // In C, we first see whether there is a tag type by the same name, in
650 // which case it's likely that the user just forget to write "enum",
651 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000652 if (!getLangOpts().CPlusPlus && !SecondTry &&
653 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
654 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000655 }
656
657 // Perform typo correction to determine if there is another name that is
658 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000659 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000660 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000661 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000662 Result.getLookupKind(), S,
Richard Smith4f605af2012-08-18 00:55:03 +0000663 &SS, *CCC)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000664 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
665 unsigned QualifiedDiag = diag::err_no_member_suggest;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000666 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
667 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000668
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000669 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000670 NamedDecl *UnderlyingFirstDecl
671 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000672 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000673 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000674 UnqualifiedDiag = diag::err_no_template_suggest;
675 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000676 } else if (UnderlyingFirstDecl &&
677 (isa<TypeDecl>(UnderlyingFirstDecl) ||
678 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
679 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000680 UnqualifiedDiag = diag::err_unknown_typename_suggest;
681 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
682 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000683
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000684 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000685 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000686 << Name << CorrectedQuotedStr
687 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
David Blaikie04ea41c2012-10-12 20:00:44 +0000688 else // FIXME: is this even reachable? Test it.
Douglas Gregor5e16c162011-04-27 03:47:06 +0000689 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000690 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000691 << SS.getRange()
David Blaikie04ea41c2012-10-12 20:00:44 +0000692 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
693 CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000694
695 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000696 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000697
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000698 // Typo correction corrected to a keyword.
699 if (Corrected.isKeyword())
700 return Corrected.getCorrectionAsIdentifierInfo();
701
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000702 // Also update the LookupResult...
703 // FIXME: This should probably go away at some point
704 Result.clear();
705 Result.setLookupName(Corrected.getCorrection());
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000706 if (FirstDecl) {
707 Result.addDecl(FirstDecl);
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000708 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
709 << CorrectedQuotedStr;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000710 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000711
712 // If we found an Objective-C instance variable, let
713 // LookupInObjCMethod build the appropriate expression to
714 // reference the ivar.
715 // FIXME: This is a gross hack.
716 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
717 Result.clear();
718 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000719 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000720 }
721
722 goto Corrected;
723 }
724 }
725
726 // We failed to correct; just fall through and let the parser deal with it.
727 Result.suppressDiagnostics();
728 return NameClassification::Unknown();
729
Abramo Bagnara7945c982012-01-27 09:46:47 +0000730 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000731 // We performed name lookup into the current instantiation, and there were
732 // dependent bases, so we treat this result the same way as any other
733 // dependent nested-name-specifier.
734
735 // C++ [temp.res]p2:
736 // A name used in a template declaration or definition and that is
737 // dependent on a template-parameter is assumed not to name a type
738 // unless the applicable name lookup finds a type name or the name is
739 // qualified by the keyword typename.
740 //
741 // FIXME: If the next token is '<', we might want to ask the parser to
742 // perform some heroics to see if we actually have a
743 // template-argument-list, which would indicate a missing 'template'
744 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000745 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
746 NameInfo, IsAddressOfOperand,
747 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000748 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000749
750 case LookupResult::Found:
751 case LookupResult::FoundOverloaded:
752 case LookupResult::FoundUnresolvedValue:
753 break;
754
755 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000756 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000757 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000758 // C++ [temp.local]p3:
759 // A lookup that finds an injected-class-name (10.2) can result in an
760 // ambiguity in certain cases (for example, if it is found in more than
761 // one base class). If all of the injected-class-names that are found
762 // refer to specializations of the same class template, and if the name
763 // is followed by a template-argument-list, the reference refers to the
764 // class template itself and not a specialization thereof, and is not
765 // ambiguous.
766 //
767 // This filtering can make an ambiguous result into an unambiguous one,
768 // so try again after filtering out template names.
769 FilterAcceptableTemplateNames(Result);
770 if (!Result.isAmbiguous()) {
771 IsFilteredTemplateName = true;
772 break;
773 }
774 }
775
776 // Diagnose the ambiguity and return an error.
777 return NameClassification::Error();
778 }
779
David Blaikiebbafb8a2012-03-11 07:00:24 +0000780 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000781 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
782 // C++ [temp.names]p3:
783 // After name lookup (3.4) finds that a name is a template-name or that
784 // an operator-function-id or a literal- operator-id refers to a set of
785 // overloaded functions any member of which is a function template if
786 // this is followed by a <, the < is always taken as the delimiter of a
787 // template-argument-list and never as the less-than operator.
788 if (!IsFilteredTemplateName)
789 FilterAcceptableTemplateNames(Result);
790
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000791 if (!Result.empty()) {
792 bool IsFunctionTemplate;
793 TemplateName Template;
794 if (Result.end() - Result.begin() > 1) {
795 IsFunctionTemplate = true;
796 Template = Context.getOverloadedTemplateName(Result.begin(),
797 Result.end());
798 } else {
799 TemplateDecl *TD
800 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
801 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
802
803 if (SS.isSet() && !SS.isInvalid())
804 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000805 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000806 TD);
807 else
808 Template = TemplateName(TD);
809 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000810
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000811 if (IsFunctionTemplate) {
812 // Function templates always go through overload resolution, at which
813 // point we'll perform the various checks (e.g., accessibility) we need
814 // to based on which function we selected.
815 Result.suppressDiagnostics();
816
817 return NameClassification::FunctionTemplate(Template);
818 }
819
820 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000821 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000822 }
Richard Smith4f605af2012-08-18 00:55:03 +0000823
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000824 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000825 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
826 DiagnoseUseOfDecl(Type, NameLoc);
827 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000828 if (SS.isNotEmpty())
829 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000830 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000831 }
Richard Smith4f605af2012-08-18 00:55:03 +0000832
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000833 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
834 if (!Class) {
835 // FIXME: It's unfortunate that we don't have a Type node for handling this.
836 if (ObjCCompatibleAliasDecl *Alias
837 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
838 Class = Alias->getClassInterface();
839 }
840
841 if (Class) {
842 DiagnoseUseOfDecl(Class, NameLoc);
843
844 if (NextToken.is(tok::period)) {
845 // Interface. <something> is parsed as a property reference expression.
846 // Just return "unknown" as a fall-through for now.
847 Result.suppressDiagnostics();
848 return NameClassification::Unknown();
849 }
850
851 QualType T = Context.getObjCInterfaceType(Class);
852 return ParsedType::make(T);
853 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000854
Richard Smith4f605af2012-08-18 00:55:03 +0000855 // We can have a type template here if we're classifying a template argument.
856 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
857 return NameClassification::TypeTemplate(
858 TemplateName(cast<TemplateDecl>(FirstDecl)));
859
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000860 // Check for a tag type hidden by a non-type decl in a few cases where it
861 // seems likely a type is wanted instead of the non-type that was found.
Richard Smith4f605af2012-08-18 00:55:03 +0000862 if (!getLangOpts().ObjC1) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000863 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
864 if ((NextToken.is(tok::identifier) ||
865 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
866 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000867 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
868 DiagnoseUseOfDecl(Type, NameLoc);
869 QualType T = Context.getTypeDeclType(Type);
870 if (SS.isNotEmpty())
871 return buildNestedType(*this, SS, T, NameLoc);
872 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000873 }
874 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000875
Richard Smith4f605af2012-08-18 00:55:03 +0000876 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000877 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000878
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000879 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
880 return BuildDeclarationNameExpr(SS, Result, ADL);
881}
882
John McCall5ed6e8f2009-08-18 00:00:49 +0000883// Determines the context to return to after temporarily entering a
884// context. This depends in an unnecessarily complicated way on the
885// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000886DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000887
John McCall5ed6e8f2009-08-18 00:00:49 +0000888 // Functions defined inline within classes aren't parsed until we've
889 // finished parsing the top-level class, so the top-level class is
890 // the context we'll need to return to.
891 if (isa<FunctionDecl>(DC)) {
892 DC = DC->getLexicalParent();
893
894 // A function not defined within a class will always return to its
895 // lexical context.
896 if (!isa<CXXRecordDecl>(DC))
897 return DC;
898
899 // A C++ inline method/friend is parsed *after* the topmost class
900 // it was declared in is fully parsed ("complete"); the topmost
901 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000902 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000903 DC = RD;
904
905 // Return the declaration context of the topmost class the inline method is
906 // declared in.
907 return DC;
908 }
909
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000910 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000911}
912
Douglas Gregor91f84212008-12-11 16:49:14 +0000913void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000914 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000915 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000916 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000917 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000918}
919
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000920void Sema::PopDeclContext() {
921 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000922
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000923 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000924 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000925}
926
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000927/// EnterDeclaratorContext - Used when we must lookup names in the context
928/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000929///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000930void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000931 // C++0x [basic.lookup.unqual]p13:
932 // A name used in the definition of a static data member of class
933 // X (after the qualified-id of the static member) is looked up as
934 // if the name was used in a member function of X.
935 // C++0x [basic.lookup.unqual]p14:
936 // If a variable member of a namespace is defined outside of the
937 // scope of its namespace then any name used in the definition of
938 // the variable member (after the declarator-id) is looked up as
939 // if the definition of the variable member occurred in its
940 // namespace.
941 // Both of these imply that we should push a scope whose context
942 // is the semantic context of the declaration. We can't use
943 // PushDeclContext here because that context is not necessarily
944 // lexically contained in the current context. Fortunately,
945 // the containing scope should have the appropriate information.
946
947 assert(!S->getEntity() && "scope already has entity");
948
949#ifndef NDEBUG
950 Scope *Ancestor = S->getParent();
951 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
952 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
953#endif
954
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000955 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000956 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000957}
958
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000959void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000960 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000961
John McCall6df5fef2009-12-19 10:49:29 +0000962 // Switch back to the lexical context. The safety of this is
963 // enforced by an assert in EnterDeclaratorContext.
964 Scope *Ancestor = S->getParent();
965 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
966 CurContext = (DeclContext*) Ancestor->getEntity();
967
968 // We don't need to do anything with the scope, which is going to
969 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000970}
971
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000972
973void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
974 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
975 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
976 // We assume that the caller has already called
977 // ActOnReenterTemplateScope
978 FD = TFD->getTemplatedDecl();
979 }
980 if (!FD)
981 return;
982
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000983 // Same implementation as PushDeclContext, but enters the context
984 // from the lexical parent, rather than the top-level class.
985 assert(CurContext == FD->getLexicalParent() &&
986 "The next DeclContext should be lexically contained in the current one.");
987 CurContext = FD;
988 S->setEntity(CurContext);
989
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000990 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
991 ParmVarDecl *Param = FD->getParamDecl(P);
992 // If the parameter has an identifier, then add it to the scope
993 if (Param->getIdentifier()) {
994 S->AddDecl(Param);
995 IdResolver.AddDecl(Param);
996 }
997 }
998}
999
1000
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001001void Sema::ActOnExitFunctionContext() {
1002 // Same implementation as PopDeclContext, but returns to the lexical parent,
1003 // rather than the top-level class.
1004 assert(CurContext && "DeclContext imbalance!");
1005 CurContext = CurContext->getLexicalParent();
1006 assert(CurContext && "Popped translation unit!");
1007}
1008
1009
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001010/// \brief Determine whether we allow overloading of the function
1011/// PrevDecl with another declaration.
1012///
1013/// This routine determines whether overloading is possible, not
1014/// whether some new function is actually an overload. It will return
1015/// true in C++ (where we can always provide overloads) or, as an
1016/// extension, in C when the previous function is already an
1017/// overloaded function declaration or has the "overloadable"
1018/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001019static bool AllowOverloadingOfFunction(LookupResult &Previous,
1020 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001021 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001022 return true;
1023
John McCall1f82f242009-11-18 22:49:29 +00001024 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001025 return true;
1026
John McCall1f82f242009-11-18 22:49:29 +00001027 return (Previous.getResultKind() == LookupResult::Found
1028 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001029}
1030
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001031/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001032void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001033 // Move up the scope chain until we find the nearest enclosing
1034 // non-transparent context. The declaration will be introduced into this
1035 // scope.
Mike Stump11289f42009-09-09 15:08:12 +00001036 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +00001037 ((DeclContext *)S->getEntity())->isTransparentContext())
1038 S = S->getParent();
1039
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001040 // Add scoped declarations into their context, so that they can be
1041 // found later. Declarations without a context won't be inserted
1042 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001043 if (AddToContext)
1044 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001045
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001046 // Out-of-line definitions shouldn't be pushed into scope in C++.
1047 // Out-of-line variable and function definitions shouldn't even in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001048 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001049 D->isOutOfLine() &&
1050 !D->getDeclContext()->getRedeclContext()->Equals(
1051 D->getLexicalDeclContext()->getRedeclContext()))
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001052 return;
1053
1054 // Template instantiations should also not be pushed into scope.
1055 if (isa<FunctionDecl>(D) &&
1056 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001057 return;
1058
John McCall9f3059a2009-10-09 21:13:30 +00001059 // If this replaces anything in the current scope,
1060 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1061 IEnd = IdResolver.end();
1062 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001063 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1064 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001065 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001066
John McCall9f3059a2009-10-09 21:13:30 +00001067 // Should only need to replace one decl.
1068 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001069 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001070 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071
John McCall48871652010-08-21 09:40:31 +00001072 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001073
1074 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1075 // Implicitly-generated labels may end up getting generated in an order that
1076 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1077 // the label at the appropriate place in the identifier chain.
1078 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001079 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001080 if (IDC == CurContext) {
1081 if (!S->isDeclScope(*I))
1082 continue;
1083 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001084 break;
1085 }
1086
Douglas Gregor46c04e72011-03-16 16:39:03 +00001087 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001088 } else {
1089 IdResolver.AddDecl(D);
1090 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001091}
1092
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001093void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1094 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1095 TUScope->AddDecl(D);
1096}
1097
Douglas Gregordb446112011-03-07 16:54:27 +00001098bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1099 bool ExplicitInstantiationOrSpecialization) {
1100 return IdResolver.isDeclInScope(D, Ctx, Context, S,
1101 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +00001102}
1103
John McCallcc14d1f2010-08-24 08:50:51 +00001104Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1105 DeclContext *TargetDC = DC->getPrimaryContext();
1106 do {
1107 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1108 if (ScopeDC->getPrimaryContext() == TargetDC)
1109 return S;
1110 } while ((S = S->getParent()));
1111
1112 return 0;
1113}
1114
John McCall1f82f242009-11-18 22:49:29 +00001115static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1116 DeclContext*,
1117 ASTContext&);
1118
1119/// Filters out lookup results that don't fall within the given scope
1120/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00001121void Sema::FilterLookupForScope(LookupResult &R,
1122 DeclContext *Ctx, Scope *S,
1123 bool ConsiderLinkage,
1124 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +00001125 LookupResult::Filter F = R.makeFilter();
1126 while (F.hasNext()) {
1127 NamedDecl *D = F.next();
1128
Richard Smith3f1b5d02011-05-05 21:57:07 +00001129 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +00001130 continue;
1131
1132 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00001133 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001134 continue;
1135
1136 F.erase();
1137 }
1138
1139 F.done();
1140}
1141
1142static bool isUsingDecl(NamedDecl *D) {
1143 return isa<UsingShadowDecl>(D) ||
1144 isa<UnresolvedUsingTypenameDecl>(D) ||
1145 isa<UnresolvedUsingValueDecl>(D);
1146}
1147
1148/// Removes using shadow declarations from the lookup results.
1149static void RemoveUsingDecls(LookupResult &R) {
1150 LookupResult::Filter F = R.makeFilter();
1151 while (F.hasNext())
1152 if (isUsingDecl(F.next()))
1153 F.erase();
1154
1155 F.done();
1156}
1157
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001158/// \brief Check for this common pattern:
1159/// @code
1160/// class S {
1161/// S(const S&); // DO NOT IMPLEMENT
1162/// void operator=(const S&); // DO NOT IMPLEMENT
1163/// };
1164/// @endcode
1165static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1166 // FIXME: Should check for private access too but access is set after we get
1167 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001168 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001169 return false;
1170
1171 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1172 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001173 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1174 return Method->isCopyAssignmentOperator();
1175 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001176}
1177
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001178bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1179 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001180
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001181 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1182 return false;
1183
1184 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001185 if (D->getDeclContext()->isDependentContext() ||
1186 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001187 return false;
1188
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001189 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001190 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1191 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001192
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001193 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1194 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1195 return false;
1196 } else {
1197 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +00001198 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001199 FD->isInlineSpecified())
1200 return false;
1201 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001202
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001203 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001204 Context.DeclMustBeEmitted(FD))
1205 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001206 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Richard Smith59a8e492012-10-28 07:39:29 +00001207 // Don't warn on variables of const-qualified or reference type, since their
1208 // values can be used even if though they're not odr-used, and because const
1209 // qualified variables can appear in headers in contexts where they're not
1210 // intended to be used.
1211 // FIXME: Use more principled rules for these exemptions.
John McCalld37d35b2010-10-27 01:41:35 +00001212 if (!VD->isFileVarDecl() ||
Richard Smith59a8e492012-10-28 07:39:29 +00001213 VD->getType().isConstQualified() ||
1214 VD->getType()->isReferenceType() ||
John McCalld37d35b2010-10-27 01:41:35 +00001215 Context.DeclMustBeEmitted(VD))
1216 return false;
1217
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001218 if (VD->isStaticDataMember() &&
1219 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1220 return false;
1221
John McCalld37d35b2010-10-27 01:41:35 +00001222 } else {
1223 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001224 }
1225
John McCalld37d35b2010-10-27 01:41:35 +00001226 // Only warn for unused decls internal to the translation unit.
1227 if (D->getLinkage() == ExternalLinkage)
1228 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001229
John McCalld37d35b2010-10-27 01:41:35 +00001230 return true;
1231}
1232
1233void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001234 if (!D)
1235 return;
1236
1237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1238 const FunctionDecl *First = FD->getFirstDeclaration();
1239 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1240 return; // First should already be in the vector.
1241 }
1242
1243 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1244 const VarDecl *First = VD->getFirstDeclaration();
1245 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1246 return; // First should already be in the vector.
1247 }
1248
David Blaikie3d8edc22012-05-26 05:35:39 +00001249 if (ShouldWarnIfUnusedFileScopedDecl(D))
1250 UnusedFileScopedDecls.push_back(D);
1251}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001252
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001253static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001254 if (D->isInvalidDecl())
1255 return false;
1256
Eli Friedmanc09e0552012-01-13 23:41:25 +00001257 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001258 return false;
John McCall67da35c2010-02-04 22:26:26 +00001259
Chris Lattnercab02a62011-02-17 20:34:02 +00001260 if (isa<LabelDecl>(D))
1261 return true;
1262
John McCall67da35c2010-02-04 22:26:26 +00001263 // White-list anything that isn't a local variable.
1264 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1265 !D->getDeclContext()->isFunctionOrMethod())
1266 return false;
1267
1268 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001269 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001270
1271 // White-list anything with an __attribute__((unused)) type.
1272 QualType Ty = VD->getType();
1273
1274 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001275 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001276 if (TT->getDecl()->hasAttr<UnusedAttr>())
1277 return false;
1278 }
1279
Douglas Gregor14f232e2010-05-08 23:05:03 +00001280 // If we failed to complete the type for some reason, or if the type is
1281 // dependent, don't diagnose the variable.
1282 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001283 return false;
1284
John McCallcef15822010-03-31 02:47:45 +00001285 if (const TagType *TT = Ty->getAs<TagType>()) {
1286 const TagDecl *Tag = TT->getDecl();
1287 if (Tag->hasAttr<UnusedAttr>())
1288 return false;
1289
1290 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Rafael Espindola7c23b082012-01-06 04:54:01 +00001291 if (!RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001292 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001293
1294 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001295 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1296 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001297 const CXXConstructExpr *Construct =
1298 dyn_cast<CXXConstructExpr>(Init);
1299 if (Construct && !Construct->isElidable()) {
1300 CXXConstructorDecl *CD = Construct->getConstructor();
1301 if (!CD->isTrivial())
1302 return false;
1303 }
1304 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001305 }
1306 }
John McCallcef15822010-03-31 02:47:45 +00001307
1308 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001309 }
1310
John McCall67da35c2010-02-04 22:26:26 +00001311 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001312}
1313
Anna Zaks964f4c62011-07-28 20:52:06 +00001314static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1315 FixItHint &Hint) {
1316 if (isa<LabelDecl>(D)) {
1317 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001318 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001319 if (AfterColon.isInvalid())
1320 return;
1321 Hint = FixItHint::CreateRemoval(CharSourceRange::
1322 getCharRange(D->getLocStart(), AfterColon));
1323 }
1324 return;
1325}
1326
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001327/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1328/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001329void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001330 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001331 if (!ShouldDiagnoseUnusedDecl(D))
1332 return;
1333
Anna Zaks964f4c62011-07-28 20:52:06 +00001334 GenerateFixForUnusedDecl(D, Context, Hint);
1335
Chris Lattnercab02a62011-02-17 20:34:02 +00001336 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001337 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001338 DiagID = diag::warn_unused_exception_param;
1339 else if (isa<LabelDecl>(D))
1340 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001341 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001342 DiagID = diag::warn_unused_variable;
1343
Anna Zaks964f4c62011-07-28 20:52:06 +00001344 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001345}
1346
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001347static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1348 // Verify that we have no forward references left. If so, there was a goto
1349 // or address of a label taken, but no definition of it. Label fwd
1350 // definitions are indicated with a null substmt.
1351 if (L->getStmt() == 0)
1352 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1353}
1354
Steve Naroffc62adb62007-10-09 22:01:59 +00001355void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001356 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001357 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001358 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001359
Chris Lattner302b4be2006-11-19 02:31:38 +00001360 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1361 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001362 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001363 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001364
Douglas Gregor91f84212008-12-11 16:49:14 +00001365 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1366 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001367
Douglas Gregor91f84212008-12-11 16:49:14 +00001368 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001369
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001370 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001371 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001372 DiagnoseUnusedDecl(D);
1373
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001374 // If this was a forward reference to a label, verify it was defined.
1375 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1376 CheckPoppedLabel(LD, *this);
1377
Douglas Gregor91f84212008-12-11 16:49:14 +00001378 // Remove this name from our lexical scope.
1379 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001380 }
1381}
1382
James Molloy6f8780b2012-02-29 10:24:19 +00001383void Sema::ActOnStartFunctionDeclarator() {
1384 ++InFunctionDeclarator;
1385}
1386
1387void Sema::ActOnEndFunctionDeclarator() {
1388 assert(InFunctionDeclarator);
1389 --InFunctionDeclarator;
1390}
1391
Douglas Gregor1c283312010-08-11 12:19:30 +00001392/// \brief Look for an Objective-C class in the translation unit.
1393///
1394/// \param Id The name of the Objective-C class we're looking for. If
1395/// typo-correction fixes this name, the Id will be updated
1396/// to the fixed name.
1397///
1398/// \param IdLoc The location of the name in the translation unit.
1399///
James Dennett41725122012-06-22 10:16:05 +00001400/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001401/// if there is no class with the given name.
1402///
1403/// \returns The declaration of the named Objective-C class, or NULL if the
1404/// class could not be found.
1405ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1406 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001407 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001408 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1409 // creation from this context.
1410 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1411
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001412 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001413 // Perform typo correction at the given location, but only if we
1414 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001415 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1416 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1417 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001418 Validator)) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001419 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001420 Diag(IdLoc, diag::err_undef_interface_suggest)
1421 << Id << IDecl->getDeclName()
1422 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1423 Diag(IDecl->getLocation(), diag::note_previous_decl)
1424 << IDecl->getDeclName();
1425
1426 Id = IDecl->getIdentifier();
1427 }
1428 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001429 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1430 // This routine must always return a class definition, if any.
1431 if (Def && Def->getDefinition())
1432 Def = Def->getDefinition();
1433 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001434}
1435
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001436/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1437/// from S, where a non-field would be declared. This routine copes
1438/// with the difference between C and C++ scoping rules in structs and
1439/// unions. For example, the following code is well-formed in C but
1440/// ill-formed in C++:
1441/// @code
1442/// struct S6 {
1443/// enum { BAR } e;
1444/// };
Mike Stump11289f42009-09-09 15:08:12 +00001445///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001446/// void test_S6() {
1447/// struct S6 a;
1448/// a.e = BAR;
1449/// }
1450/// @endcode
1451/// For the declaration of BAR, this routine will return a different
1452/// scope. The scope S will be the scope of the unnamed enumeration
1453/// within S6. In C++, this routine will return the scope associated
1454/// with S6, because the enumeration's scope is a transparent
1455/// context but structures can contain non-field names. In C, this
1456/// routine will return the translation unit scope, since the
1457/// enumeration's scope is a transparent context and structures cannot
1458/// contain non-field names.
1459Scope *Sema::getNonFieldDeclScope(Scope *S) {
1460 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001461 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001462 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001463 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001464 S = S->getParent();
1465 return S;
1466}
1467
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001468/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1469/// file scope. lazily create a decl for it. ForRedeclaration is true
1470/// if we're creating this built-in in anticipation of redeclaring the
1471/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001472NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001473 Scope *S, bool ForRedeclaration,
1474 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001475 Builtin::ID BID = (Builtin::ID)bid;
1476
Chris Lattnerecd79c62009-06-14 00:45:47 +00001477 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001478 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001479 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001480 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001481 // Okay
1482 break;
1483
Mike Stump93246cc2009-07-28 23:57:15 +00001484 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001485 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001486 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001487 << Context.BuiltinInfo.GetName(BID);
1488 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001489
Mike Stump93246cc2009-07-28 23:57:15 +00001490 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001491 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001492 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001493 << Context.BuiltinInfo.GetName(BID);
1494 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001495
1496 case ASTContext::GE_Missing_ucontext:
1497 if (ForRedeclaration)
1498 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1499 << Context.BuiltinInfo.GetName(BID);
1500 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001501 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001502
1503 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1504 Diag(Loc, diag::ext_implicit_lib_function_decl)
1505 << Context.BuiltinInfo.GetName(BID)
1506 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001507 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001508 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001509 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001510 Diag(Loc, diag::note_please_include_header)
1511 << Context.BuiltinInfo.getHeaderName(BID)
1512 << Context.BuiltinInfo.GetName(BID);
1513 }
1514
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001515 FunctionDecl *New = FunctionDecl::Create(Context,
1516 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001517 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001518 SC_Extern,
1519 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001520 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001521 New->setImplicit();
1522
Chris Lattner4dd27102008-05-05 22:18:14 +00001523 // Create Decl objects for each parameter, adding them to the
1524 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001525 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001526 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001527 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1528 ParmVarDecl *parm =
1529 ParmVarDecl::Create(Context, New, SourceLocation(),
1530 SourceLocation(), 0,
1531 FT->getArgType(i), /*TInfo=*/0,
1532 SC_None, SC_None, 0);
1533 parm->setScopeInfo(0, i);
1534 Params.push_back(parm);
1535 }
David Blaikie9c70e042011-09-21 18:16:56 +00001536 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
1539 AddKnownFunctionAttributes(New);
1540
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001541 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001542 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1543 // relate Scopes to DeclContexts, and probably eliminate CurContext
1544 // entirely, but we're not there yet.
1545 DeclContext *SavedContext = CurContext;
1546 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001547 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001548 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001549 return New;
1550}
1551
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001552bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1553 QualType OldType;
1554 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1555 OldType = OldTypedef->getUnderlyingType();
1556 else
1557 OldType = Context.getTypeDeclType(Old);
1558 QualType NewType = New->getUnderlyingType();
1559
Douglas Gregoraab36982012-01-11 22:33:48 +00001560 if (NewType->isVariablyModifiedType()) {
1561 // Must not redefine a typedef with a variably-modified type.
1562 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1563 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1564 << Kind << NewType;
1565 if (Old->getLocation().isValid())
1566 Diag(Old->getLocation(), diag::note_previous_definition);
1567 New->setInvalidDecl();
1568 return true;
1569 }
1570
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001571 if (OldType != NewType &&
1572 !OldType->isDependentType() &&
1573 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001574 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001575 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1576 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1577 << Kind << NewType << OldType;
1578 if (Old->getLocation().isValid())
1579 Diag(Old->getLocation(), diag::note_previous_definition);
1580 New->setInvalidDecl();
1581 return true;
1582 }
1583 return false;
1584}
1585
Richard Smithdda56e42011-04-15 14:24:37 +00001586/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001587/// same name and scope as a previous declaration 'Old'. Figure out
1588/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001589/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001590///
Richard Smithdda56e42011-04-15 14:24:37 +00001591void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001592 // If the new decl is known invalid already, don't bother doing any
1593 // merging checks.
1594 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001595
Steve Naroff44cfcb62008-09-09 14:32:20 +00001596 // Allow multiple definitions for ObjC built-in typedefs.
1597 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001598 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001599 const IdentifierInfo *TypeID = New->getIdentifier();
1600 switch (TypeID->getLength()) {
1601 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001602 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001603 {
1604 if (!TypeID->isStr("id"))
1605 break;
1606 QualType T = New->getUnderlyingType();
1607 if (!T->isPointerType())
1608 break;
1609 if (!T->isVoidPointerType()) {
1610 QualType PT = T->getAs<PointerType>()->getPointeeType();
1611 if (!PT->isStructureType())
1612 break;
1613 }
1614 Context.setObjCIdRedefinitionType(T);
1615 // Install the built-in type for 'id', ignoring the current definition.
1616 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1617 return;
1618 }
Chris Lattner66e32812008-11-20 05:41:43 +00001619 case 5:
1620 if (!TypeID->isStr("Class"))
1621 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001622 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001623 // Install the built-in type for 'Class', ignoring the current definition.
1624 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001625 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001626 case 3:
1627 if (!TypeID->isStr("SEL"))
1628 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001629 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001630 // Install the built-in type for 'SEL', ignoring the current definition.
1631 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001632 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001633 }
1634 // Fall through - the typedef name was not a builtin type.
1635 }
John McCall1f82f242009-11-18 22:49:29 +00001636
Douglas Gregorfb034662009-01-28 17:15:10 +00001637 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001638 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1639 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001640 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001641 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001642
1643 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001644 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001645 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001646
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001647 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001648 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001649
John McCall1f82f242009-11-18 22:49:29 +00001650 // If the old declaration is invalid, just give up here.
1651 if (Old->isInvalidDecl())
1652 return New->setInvalidDecl();
1653
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001654 // If the typedef types are not identical, reject them in all languages and
1655 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001656 if (isIncompatibleTypedef(Old, New))
1657 return;
Mike Stump11289f42009-09-09 15:08:12 +00001658
John McCall91f1a022009-12-30 00:31:22 +00001659 // The types match. Link up the redeclaration chain if the old
1660 // declaration was a typedef.
Richard Smithdda56e42011-04-15 14:24:37 +00001661 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1662 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001663
David Blaikiebbafb8a2012-03-11 07:00:24 +00001664 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001665 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001666
David Blaikiebbafb8a2012-03-11 07:00:24 +00001667 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001668 // C++ [dcl.typedef]p2:
1669 // In a given non-class scope, a typedef specifier can be used to
1670 // redefine the name of any type declared in that scope to refer
1671 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001672 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001673 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001674
1675 // C++0x [dcl.typedef]p4:
1676 // In a given class scope, a typedef specifier can be used to redefine
1677 // any class-name declared in that scope that is not also a typedef-name
1678 // to refer to the type to which it already refers.
1679 //
1680 // This wording came in via DR424, which was a correction to the
1681 // wording in DR56, which accidentally banned code like:
1682 //
1683 // struct S {
1684 // typedef struct A { } A;
1685 // };
1686 //
1687 // in the C++03 standard. We implement the C++0x semantics, which
1688 // allow the above but disallow
1689 //
1690 // struct S {
1691 // typedef int I;
1692 // typedef int I;
1693 // };
1694 //
1695 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001696 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001697 return;
1698
Chris Lattner2581fc32009-04-17 22:04:20 +00001699 Diag(New->getLocation(), diag::err_redefinition)
1700 << New->getDeclName();
1701 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001702 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001703 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001704
Douglas Gregor7363fb02012-01-11 04:25:01 +00001705 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001706 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001707 return;
1708
Chris Lattner2581fc32009-04-17 22:04:20 +00001709 // If we have a redefinition of a typedef in C, emit a warning. This warning
1710 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001711 // -Wtypedef-redefinition. If either the original or the redefinition is
1712 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001713 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001714 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1715 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001716 return;
Mike Stump11289f42009-09-09 15:08:12 +00001717
Chris Lattner2581fc32009-04-17 22:04:20 +00001718 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1719 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001720 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001721 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001722}
1723
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001724/// DeclhasAttr - returns true if decl Declaration already has the target
1725/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001726static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001727DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001728 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1729 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1730 // responsible for making sure they are consistent.
1731 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1732 if (AA)
1733 return false;
1734
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001735 // The following thread safety attributes can also be duplicated.
1736 switch (A->getKind()) {
1737 case attr::ExclusiveLocksRequired:
1738 case attr::SharedLocksRequired:
1739 case attr::LocksExcluded:
1740 case attr::ExclusiveLockFunction:
1741 case attr::SharedLockFunction:
1742 case attr::UnlockFunction:
1743 case attr::ExclusiveTrylockFunction:
1744 case attr::SharedTrylockFunction:
1745 case attr::GuardedBy:
1746 case attr::PtGuardedBy:
1747 case attr::AcquiredBefore:
1748 case attr::AcquiredAfter:
1749 return false;
DeLesley Hutchins6c6e8592012-10-12 21:49:04 +00001750 default:
1751 ;
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001752 }
1753
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001754 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001755 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001756 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1757 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001758 if (Ann) {
1759 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1760 return true;
1761 continue;
1762 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001763 // FIXME: Don't hardcode this check
1764 if (OA && isa<OwnershipAttr>(*i))
1765 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001766 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001767 }
Chris Lattner84966392008-03-03 03:28:21 +00001768
1769 return false;
1770}
1771
Rafael Espindolac67f2232012-05-10 02:50:16 +00001772bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001773 InheritableAttr *NewAttr = NULL;
Rafael Espindolac67f2232012-05-10 02:50:16 +00001774 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001775 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1776 AA->getIntroduced(), AA->getDeprecated(),
1777 AA->getObsoleted(), AA->getUnavailable(),
1778 AA->getMessage());
1779 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1780 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
1781 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1782 NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
1783 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1784 NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
1785 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1786 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
1787 FA->getFormatIdx(), FA->getFirstArg());
1788 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1789 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
1790 else if (!DeclHasAttr(D, Attr))
1791 NewAttr = cast<InheritableAttr>(Attr->clone(Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001792
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001793 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001794 NewAttr->setInherited(true);
1795 D->addAttr(NewAttr);
1796 return true;
1797 }
1798
1799 return false;
1800}
1801
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001802static const Decl *getDefinition(const Decl *D) {
1803 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001804 return TD->getDefinition();
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001805 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001806 return VD->getDefinition();
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001807 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001808 const FunctionDecl* Def;
1809 if (FD->hasBody(Def))
1810 return Def;
1811 }
1812 return NULL;
1813}
1814
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001815static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1816 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
1817 I != E; ++I) {
1818 Attr *Attribute = *I;
1819 if (Attribute->getKind() == Kind)
1820 return true;
1821 }
1822 return false;
1823}
1824
1825/// checkNewAttributesAfterDef - If we already have a definition, check that
1826/// there are no new attributes in this declaration.
1827static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
1828 if (!New->hasAttrs())
1829 return;
1830
1831 const Decl *Def = getDefinition(Old);
1832 if (!Def || Def == New)
1833 return;
1834
1835 AttrVec &NewAttributes = New->getAttrs();
1836 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
1837 const Attr *NewAttribute = NewAttributes[I];
1838 if (hasAttribute(Def, NewAttribute->getKind())) {
1839 ++I;
1840 continue; // regular attr merging will take care of validating this.
1841 }
1842 S.Diag(NewAttribute->getLocation(),
1843 diag::warn_attribute_precede_definition);
1844 S.Diag(Def->getLocation(), diag::note_previous_definition);
1845 NewAttributes.erase(NewAttributes.begin() + I);
1846 --E;
1847 }
1848}
1849
John McCallf79e87d2011-03-02 04:00:57 +00001850/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Douglas Gregor32c17572012-01-01 20:30:41 +00001851void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1852 bool MergeDeprecation) {
Rafael Espindola36191042012-05-18 01:47:00 +00001853 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001854 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00001855
Douglas Gregor32c17572012-01-01 20:30:41 +00001856 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001857 return;
John McCallf79e87d2011-03-02 04:00:57 +00001858
Douglas Gregor32c17572012-01-01 20:30:41 +00001859 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00001860
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001861 // Ensure that any moving of objects within the allocated map is done before
1862 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00001863 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00001864
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001865 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00001866 i = Old->specific_attr_begin<InheritableAttr>(),
1867 e = Old->specific_attr_end<InheritableAttr>();
1868 i != e; ++i) {
Douglas Gregorb1fa1482011-09-23 20:23:42 +00001869 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor32c17572012-01-01 20:30:41 +00001870 if (!MergeDeprecation &&
Douglas Gregorb1fa1482011-09-23 20:23:42 +00001871 (isa<DeprecatedAttr>(*i) ||
1872 isa<UnavailableAttr>(*i) ||
1873 isa<AvailabilityAttr>(*i)))
John McCalld2930c22011-07-22 02:45:48 +00001874 continue;
1875
Rafael Espindolac67f2232012-05-10 02:50:16 +00001876 if (mergeDeclAttribute(New, *i))
John McCallf79e87d2011-03-02 04:00:57 +00001877 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001878 }
John McCallf79e87d2011-03-02 04:00:57 +00001879
Douglas Gregor32c17572012-01-01 20:30:41 +00001880 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00001881}
1882
1883/// mergeParamDeclAttributes - Copy attributes from the old parameter
1884/// to the new one.
1885static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1886 const ParmVarDecl *oldDecl,
1887 ASTContext &C) {
1888 if (!oldDecl->hasAttrs())
1889 return;
1890
1891 bool foundAny = newDecl->hasAttrs();
1892
1893 // Ensure that any moving of objects within the allocated map is
1894 // done before we process them.
1895 if (!foundAny) newDecl->setAttrs(AttrVec());
1896
1897 for (specific_attr_iterator<InheritableParamAttr>
1898 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1899 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1900 if (!DeclHasAttr(newDecl, *i)) {
1901 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1902 newAttr->setInherited(true);
1903 newDecl->addAttr(newAttr);
1904 foundAny = true;
1905 }
1906 }
1907
1908 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001909}
1910
Dan Gohman28ade552010-07-26 21:25:24 +00001911namespace {
1912
Douglas Gregora74a2972009-03-06 22:43:54 +00001913/// Used in MergeFunctionDecl to keep track of function parameters in
1914/// C.
1915struct GNUCompatibleParamWarning {
1916 ParmVarDecl *OldParm;
1917 ParmVarDecl *NewParm;
1918 QualType PromotedType;
1919};
1920
Dan Gohman28ade552010-07-26 21:25:24 +00001921}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001922
1923/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001924Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001925 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001926 if (Ctor->isDefaultConstructor())
1927 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001928
1929 if (Ctor->isCopyConstructor())
1930 return Sema::CXXCopyConstructor;
1931
1932 if (Ctor->isMoveConstructor())
1933 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001934 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001935 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001936 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001937 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00001938 } else if (MD->isMoveAssignmentOperator()) {
1939 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001940 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001941
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001942 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001943}
1944
Sebastian Redl243d9052010-06-09 21:17:41 +00001945/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001946/// only extern inline functions can be redefined, and even then only in
1947/// GNU89 mode.
1948static bool canRedefineFunction(const FunctionDecl *FD,
1949 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001950 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1951 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001952 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001953 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001954}
1955
John McCalla5f46fb2012-08-25 02:00:03 +00001956/// Is the given calling convention the ABI default for the given
1957/// declaration?
1958static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
1959 CallingConv ABIDefaultCC;
1960 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1961 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
1962 } else {
1963 // Free C function or a static method.
1964 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
1965 }
1966 return ABIDefaultCC == CC;
1967}
1968
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001969/// MergeFunctionDecl - We just parsed a function 'New' from
1970/// declarator D which has the same name and scope as a previous
1971/// declaration 'Old'. Figure out how to resolve this situation,
1972/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001973///
1974/// In C++, New and Old must be declarations that are not
1975/// overloaded. Use IsOverload to determine whether New and Old are
1976/// overloaded, and to select the Old declaration that New should be
1977/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001978///
1979/// Returns true if there was an error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +00001980bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001981 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001982 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001983 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001984 = dyn_cast<FunctionTemplateDecl>(OldD))
1985 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001986 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001987 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001988 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001989 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1990 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1991 Diag(Shadow->getTargetDecl()->getLocation(),
1992 diag::note_using_decl_target);
1993 Diag(Shadow->getUsingDecl()->getLocation(),
1994 diag::note_using_decl) << 0;
1995 return true;
1996 }
1997
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001998 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001999 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002000 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002001 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00002002 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002003
2004 // Determine whether the previous declaration was a definition,
2005 // implicit declaration, or a declaration.
2006 diag::kind PrevDiag;
2007 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002008 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002009 else if (Old->isImplicit())
2010 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002011 else
Chris Lattner0369c572008-11-23 23:12:31 +00002012 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002013
Chris Lattnerfc4379f2008-04-06 23:10:54 +00002014 QualType OldQType = Context.getCanonicalType(Old->getType());
2015 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002016
Charles Davisfea48452010-02-18 02:00:42 +00002017 // Don't complain about this if we're in GNU89 mode and the old function
2018 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002019 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002020 New->getStorageClass() == SC_Static &&
2021 Old->getStorageClass() != SC_Static &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002022 !canRedefineFunction(Old, getLangOpts())) {
2023 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002024 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2025 Diag(Old->getLocation(), PrevDiag);
2026 } else {
2027 Diag(New->getLocation(), diag::err_static_non_static) << New;
2028 Diag(Old->getLocation(), PrevDiag);
2029 return true;
2030 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002031 }
2032
John McCallcddbad02010-02-04 05:44:44 +00002033 // If a function is first declared with a calling convention, but is
2034 // later declared or defined without one, the second decl assumes the
2035 // calling convention of the first.
2036 //
John McCalla5f46fb2012-08-25 02:00:03 +00002037 // It's OK if a function is first declared without a calling convention,
2038 // but is later declared or defined with the default calling convention.
2039 //
John McCallcddbad02010-02-04 05:44:44 +00002040 // For the new decl, we have to look at the NON-canonical type to tell the
2041 // difference between a function that really doesn't have a calling
2042 // convention and one that is declared cdecl. That's because in
2043 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
2044 // because it is the default calling convention.
2045 //
2046 // Note also that we DO NOT return at this point, because we still have
2047 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00002048 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00002049 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00002050 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2051 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2052 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002053 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
2054 // Fast path: nothing to do.
2055
2056 // Inherit the CC from the previous declaration if it was specified
2057 // there but not here.
2058 } else if (NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00002059 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2060 RequiresAdjustment = true;
John McCalla5f46fb2012-08-25 02:00:03 +00002061
2062 // Don't complain about mismatches when the default CC is
2063 // effectively the same as the explict one.
2064 } else if (OldTypeInfo.getCC() == CC_Default &&
2065 isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
2066 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2067 RequiresAdjustment = true;
2068
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002069 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
2070 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00002071 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00002072 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002073 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2074 << (OldTypeInfo.getCC() == CC_Default)
2075 << (OldTypeInfo.getCC() == CC_Default ? "" :
2076 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00002077 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00002078 return true;
2079 }
2080
John McCallab26cfa2010-02-05 21:31:56 +00002081 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002082 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2083 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2084 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002085 }
2086
Douglas Gregor77e274f2010-06-18 21:30:25 +00002087 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002088 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2089 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2090 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002091 Diag(New->getLocation(), diag::err_regparm_mismatch)
2092 << NewType->getRegParmType()
2093 << OldType->getRegParmType();
2094 Diag(Old->getLocation(), diag::note_previous_declaration);
2095 return true;
2096 }
John McCall4f5019e2010-12-19 02:44:49 +00002097
2098 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2099 RequiresAdjustment = true;
2100 }
2101
Douglas Gregorf1404d72011-10-14 15:55:40 +00002102 // Merge ns_returns_retained attribute.
2103 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2104 if (NewTypeInfo.getProducesResult()) {
2105 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2106 Diag(Old->getLocation(), diag::note_previous_declaration);
2107 return true;
2108 }
2109
2110 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2111 RequiresAdjustment = true;
2112 }
2113
John McCall4f5019e2010-12-19 02:44:49 +00002114 if (RequiresAdjustment) {
2115 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2116 New->setType(QualType(NewType, 0));
2117 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00002118 }
2119
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002121 // (C++98 13.1p2):
2122 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002123 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002124 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00002125 QualType OldReturnType = OldType->getResultType();
2126 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002127 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002128 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002129 if (NewReturnType->isObjCObjectPointerType()
2130 && OldReturnType->isObjCObjectPointerType())
2131 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2132 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002133 if (New->isCXXClassMember() && New->isOutOfLine())
2134 Diag(New->getLocation(),
2135 diag::err_member_def_does_not_match_ret_type) << New;
2136 else
2137 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002138 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2139 return true;
2140 }
2141 else
2142 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002143 }
2144
2145 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00002146 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002147 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002148 // Preserve triviality.
2149 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002150
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002151 // MSVC allows explicit template specialization at class scope:
2152 // 2 CXMethodDecls referring to the same function will be injected.
2153 // We don't want a redeclartion error.
2154 bool IsClassScopeExplicitSpecialization =
2155 OldMethod->isFunctionTemplateSpecialization() &&
2156 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002157 bool isFriend = NewMethod->getFriendObjectKind();
2158
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002159 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2160 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002161 // -- Member function declarations with the same name and the
2162 // same parameter types cannot be overloaded if any of them
2163 // is a static member function declaration.
2164 if (OldMethod->isStatic() || NewMethod->isStatic()) {
2165 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2166 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2167 return true;
2168 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002169
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002170 // C++ [class.mem]p1:
2171 // [...] A member shall not be declared twice in the
2172 // member-specification, except that a nested class or member
2173 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002174 if (ActiveTemplateInstantiations.empty()) {
2175 unsigned NewDiag;
2176 if (isa<CXXConstructorDecl>(OldMethod))
2177 NewDiag = diag::err_constructor_redeclared;
2178 else if (isa<CXXDestructorDecl>(NewMethod))
2179 NewDiag = diag::err_destructor_redeclared;
2180 else if (isa<CXXConversionDecl>(NewMethod))
2181 NewDiag = diag::err_conv_function_redeclared;
2182 else
2183 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002184
Richard Smith57e7ff92012-07-13 04:12:04 +00002185 Diag(New->getLocation(), NewDiag);
2186 } else {
2187 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2188 << New << New->getType();
2189 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002190 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002191
2192 // Complain if this is an explicit declaration of a special
2193 // member that was initially declared implicitly.
2194 //
2195 // As an exception, it's okay to befriend such methods in order
2196 // to permit the implicit constructor/destructor/operator calls.
2197 } else if (OldMethod->isImplicit()) {
2198 if (isFriend) {
2199 NewMethod->setImplicit();
2200 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002201 Diag(NewMethod->getLocation(),
2202 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002203 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002204 return true;
2205 }
Richard Smith337a5a12012-06-08 01:30:54 +00002206 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002207 Diag(NewMethod->getLocation(),
2208 diag::err_definition_of_explicitly_defaulted_member)
2209 << getSpecialMember(OldMethod);
2210 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211 }
2212 }
2213
2214 // (C++98 8.3.5p3):
2215 // All declarations for a function shall agree exactly in both the
2216 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002217 // We also want to respect all the extended bits except noreturn.
2218
2219 // noreturn should now match unless the old type info didn't have it.
2220 QualType OldQTypeForComparison = OldQType;
2221 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2222 assert(OldQType == QualType(OldType, 0));
2223 const FunctionType *OldTypeForComparison
2224 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2225 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2226 assert(OldQTypeForComparison.isCanonical());
2227 }
2228
2229 if (OldQTypeForComparison == NewQType)
James Molloye9430032012-03-13 08:55:35 +00002230 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002231
2232 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002233 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002234
2235 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002236 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002238 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002239 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2240 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002241 const FunctionProtoType *OldProto = 0;
2242 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002243 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002244 // The old declaration provided a function prototype, but the
2245 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002246 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002247 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002248 OldProto->arg_type_end());
2249 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00002250 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00002251 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002252 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002253 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002254
2255 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002256 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002257 for (FunctionProtoType::arg_type_iterator
2258 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002259 ParamEnd = OldProto->arg_type_end();
2260 ParamType != ParamEnd; ++ParamType) {
2261 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002262 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002263 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002264 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00002265 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002266 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002267 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002268 Param->setImplicit();
2269 Params.push_back(Param);
2270 }
2271
David Blaikie9c70e042011-09-21 18:16:56 +00002272 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002273 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002274
James Molloye9430032012-03-13 08:55:35 +00002275 return MergeCompatibleFunctionDecls(New, Old, S);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002276 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002277
Douglas Gregora74a2972009-03-06 22:43:54 +00002278 // GNU C permits a K&R definition to follow a prototype declaration
2279 // if the declared types of the parameters in the K&R definition
2280 // match the types in the prototype declaration, even when the
2281 // promoted types of the parameters from the K&R definition differ
2282 // from the types in the prototype. GCC then keeps the types from
2283 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002284 //
2285 // If a variadic prototype is followed by a non-variadic K&R definition,
2286 // the K&R definition becomes variadic. This is sort of an edge case, but
2287 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2288 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002289 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002290 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002291 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002292 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002293 SmallVector<QualType, 16> ArgTypes;
2294 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002295 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002296 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002297 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002298 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002299
Douglas Gregora74a2972009-03-06 22:43:54 +00002300 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002301 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2302 NewProto->getResultType());
2303 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002304 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002305 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002306 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2307 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002308 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002309 NewProto->getArgType(Idx))) {
2310 ArgTypes.push_back(NewParm->getType());
2311 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002312 NewParm->getType(),
2313 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002314 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002315 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2316 Warnings.push_back(Warn);
2317 ArgTypes.push_back(NewParm->getType());
2318 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002319 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002320 }
2321
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002322 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002323 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2324 Diag(Warnings[Warn].NewParm->getLocation(),
2325 diag::ext_param_promoted_not_compatible_with_prototype)
2326 << Warnings[Warn].PromotedType
2327 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002328 if (Warnings[Warn].OldParm->getLocation().isValid())
2329 Diag(Warnings[Warn].OldParm->getLocation(),
2330 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002331 }
2332
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002333 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2334 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00002335 OldProto->getExtProtoInfo()));
James Molloye9430032012-03-13 08:55:35 +00002336 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregora74a2972009-03-06 22:43:54 +00002337 }
2338
2339 // Fall through to diagnose conflicting types.
2340 }
2341
Steve Naroff17832a42008-01-16 15:01:34 +00002342 // A function that has already been declared has been redeclared or defined
2343 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00002344 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002345 // The user has declared a builtin function with an incompatible
2346 // signature.
2347 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2348 // The function the user is redeclaring is a library-defined
2349 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00002350 // redeclaration, then pretend that we don't know about this
2351 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002352 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2353 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2354 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00002355 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2356 Old->setInvalidDecl();
2357 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002358 }
Steve Naroff17832a42008-01-16 15:01:34 +00002359
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002360 PrevDiag = diag::note_previous_builtin_declaration;
2361 }
2362
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002363 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002364 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002365 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002366}
2367
Douglas Gregore62c0a42009-02-24 01:23:02 +00002368/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002369/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002370///
2371/// This routine handles the merging of attributes and other
2372/// properties of function declarations form the old declaration to
2373/// the new declaration, once we know that New is in fact a
2374/// redeclaration of Old.
2375///
2376/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002377bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2378 Scope *S) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002379 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002380 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002381
2382 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00002383 if (Old->getStorageClass() != SC_Extern &&
2384 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002385 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00002386
Douglas Gregore62c0a42009-02-24 01:23:02 +00002387 // Merge "pure" flag.
2388 if (Old->isPure())
2389 New->setPure();
2390
Rafael Espindolabefe1302012-11-25 14:07:59 +00002391 // Merge "used" flag.
2392 if (Old->isUsed(false))
2393 New->setUsed();
2394
John McCallf79e87d2011-03-02 04:00:57 +00002395 // Merge attributes from the parameters. These can mismatch with K&R
2396 // declarations.
2397 if (New->getNumParams() == Old->getNumParams())
2398 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2399 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2400 Context);
2401
David Blaikiebbafb8a2012-03-11 07:00:24 +00002402 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002403 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002404
Rafael Espindola8778c282012-11-29 16:09:03 +00002405 // Merge the function types so the we get the composite types for the return
2406 // and argument types.
2407 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2408 if (!Merged.isNull())
2409 New->setType(Merged);
2410
Douglas Gregore62c0a42009-02-24 01:23:02 +00002411 return false;
2412}
2413
John McCall31168b02011-06-15 23:02:42 +00002414
John McCallf79e87d2011-03-02 04:00:57 +00002415void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002416 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002417
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002418 // Merge the attributes, including deprecated/unavailable
2419 mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
John McCallf79e87d2011-03-02 04:00:57 +00002420
2421 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002422 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2423 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002424 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002425 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002426 ni != ne && oi != oe; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00002427 mergeParamDeclAttributes(*ni, *oi, Context);
John McCalld2930c22011-07-22 02:45:48 +00002428
Douglas Gregor33823722011-06-11 01:09:30 +00002429 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00002430}
2431
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002432/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2433/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002434/// emitting diagnostics as appropriate.
2435///
2436/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002437/// to here in AddInitializerToDecl. We can't check them before the initializer
2438/// is attached.
Richard Smith30482bc2011-02-20 03:19:35 +00002439void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2440 if (New->isInvalidDecl() || Old->isInvalidDecl())
2441 return;
2442
2443 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002444 if (getLangOpts().CPlusPlus) {
Richard Smith30482bc2011-02-20 03:19:35 +00002445 AutoType *AT = New->getType()->getContainedAutoType();
2446 if (AT && !AT->isDeduced()) {
2447 // We don't know what the new type is until the initializer is attached.
2448 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002449 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2450 // These could still be something that needs exception specs checked.
2451 return MergeVarDeclExceptionSpecs(New, Old);
2452 }
Richard Smith30482bc2011-02-20 03:19:35 +00002453 // C++ [basic.link]p10:
2454 // [...] the types specified by all declarations referring to a given
2455 // object or function shall be identical, except that declarations for an
2456 // array object can specify array types that differ by the presence or
2457 // absence of a major array bound (8.3.4).
2458 else if (Old->getType()->isIncompleteArrayType() &&
2459 New->getType()->isArrayType()) {
2460 CanQual<ArrayType> OldArray
2461 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2462 CanQual<ArrayType> NewArray
2463 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2464 if (OldArray->getElementType() == NewArray->getElementType())
2465 MergedT = New->getType();
2466 } else if (Old->getType()->isArrayType() &&
2467 New->getType()->isIncompleteArrayType()) {
2468 CanQual<ArrayType> OldArray
2469 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2470 CanQual<ArrayType> NewArray
2471 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2472 if (OldArray->getElementType() == NewArray->getElementType())
2473 MergedT = Old->getType();
2474 } else if (New->getType()->isObjCObjectPointerType()
2475 && Old->getType()->isObjCObjectPointerType()) {
2476 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2477 Old->getType());
2478 }
2479 } else {
2480 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2481 }
2482 if (MergedT.isNull()) {
2483 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002484 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002485 Diag(Old->getLocation(), diag::note_previous_definition);
2486 return New->setInvalidDecl();
2487 }
2488 New->setType(MergedT);
2489}
2490
Chris Lattner01564d92007-01-27 19:27:06 +00002491/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2492/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2493/// situation, merging decls or emitting diagnostics as appropriate.
2494///
Mike Stump11289f42009-09-09 15:08:12 +00002495/// Tentative definition rules (C99 6.9.2p2) are checked by
2496/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002497/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002498///
John McCall1f82f242009-11-18 22:49:29 +00002499void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2500 // If the new decl is already invalid, don't do any other checking.
2501 if (New->isInvalidDecl())
2502 return;
Mike Stump11289f42009-09-09 15:08:12 +00002503
Chris Lattnerc511efb2007-01-27 19:32:14 +00002504 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002505 VarDecl *Old = 0;
2506 if (!Previous.isSingleResult() ||
2507 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002508 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002509 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002510 Diag(Previous.getRepresentativeDecl()->getLocation(),
2511 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002512 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002513 }
Chris Lattner84966392008-03-03 03:28:21 +00002514
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002515 // C++ [class.mem]p1:
2516 // A member shall not be declared twice in the member-specification [...]
2517 //
2518 // Here, we need only consider static data members.
2519 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2520 Diag(New->getLocation(), diag::err_duplicate_member)
2521 << New->getIdentifier();
2522 Diag(Old->getLocation(), diag::note_previous_declaration);
2523 New->setInvalidDecl();
2524 }
2525
Douglas Gregor32c17572012-01-01 20:30:41 +00002526 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00002527 // Warn if an already-declared variable is made a weak_import in a subsequent
2528 // declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002529 if (New->getAttr<WeakImportAttr>() &&
2530 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002531 !Old->getAttr<WeakImportAttr>()) {
2532 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2533 Diag(Old->getLocation(), diag::note_previous_definition);
2534 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002535 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002536 }
Chris Lattner84966392008-03-03 03:28:21 +00002537
Richard Smith30482bc2011-02-20 03:19:35 +00002538 // Merge the types.
2539 MergeVarDeclTypes(New, Old);
2540 if (New->isInvalidDecl())
2541 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002542
Steve Naroff1e787362008-01-30 00:44:01 +00002543 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002544 if (New->getStorageClass() == SC_Static &&
2545 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002546 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002547 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002548 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002551 // For an identifier declared with the storage-class specifier
2552 // extern in a scope in which a prior declaration of that
2553 // identifier is visible,23) if the prior declaration specifies
2554 // internal or external linkage, the linkage of the identifier at
2555 // the later declaration is the same as the linkage specified at
2556 // the prior declaration. If no prior declaration is visible, or
2557 // if the prior declaration specifies no linkage, then the
2558 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002559 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002560 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002561 else if (New->getStorageClass() != SC_Static &&
2562 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002563 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002564 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002565 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002566 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002567
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002568 // Check if extern is followed by non-extern and vice-versa.
2569 if (New->hasExternalStorage() &&
2570 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2571 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2572 Diag(Old->getLocation(), diag::note_previous_definition);
2573 return New->setInvalidDecl();
2574 }
2575 if (Old->hasExternalStorage() &&
2576 !New->hasLinkage() && New->isLocalVarDecl()) {
2577 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2578 Diag(Old->getLocation(), diag::note_previous_definition);
2579 return New->setInvalidDecl();
2580 }
2581
Steve Naroffa5629372008-09-17 14:05:40 +00002582 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002583
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002584 // FIXME: The test for external storage here seems wrong? We still
2585 // need to check for mismatches.
2586 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002587 // Don't complain about out-of-line definitions of static members.
2588 !(Old->getLexicalDeclContext()->isRecord() &&
2589 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002590 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002591 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002592 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002593 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002594
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002595 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2596 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2597 Diag(Old->getLocation(), diag::note_previous_definition);
2598 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2599 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2600 Diag(Old->getLocation(), diag::note_previous_definition);
2601 }
2602
Sebastian Redlf1842912010-02-02 18:35:11 +00002603 // C++ doesn't have tentative definitions, so go right ahead and check here.
2604 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002605 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00002606 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002607 (Def = Old->getDefinition())) {
2608 Diag(New->getLocation(), diag::err_redefinition)
2609 << New->getDeclName();
2610 Diag(Def->getLocation(), diag::note_previous_definition);
2611 New->setInvalidDecl();
2612 return;
2613 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002614 // c99 6.2.2 P4.
2615 // For an identifier declared with the storage-class specifier extern in a
2616 // scope in which a prior declaration of that identifier is visible, if
2617 // the prior declaration specifies internal or external linkage, the linkage
2618 // of the identifier at the later declaration is the same as the linkage
2619 // specified at the prior declaration.
2620 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002621 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002622 Old->getLinkage() == InternalLinkage &&
2623 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002624 New->setStorageClass(Old->getStorageClass());
2625
Rafael Espindolabefe1302012-11-25 14:07:59 +00002626 // Merge "used" flag.
2627 if (Old->isUsed(false))
2628 New->setUsed();
2629
Douglas Gregor0760fa12009-03-10 23:43:53 +00002630 // Keep a chain of previous declarations.
2631 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002632
2633 // Inherit access appropriately.
2634 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002635}
2636
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002637/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2638/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002639Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002640 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002641 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002642}
2643
2644/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2645/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2646/// parameters to cope with template friend declarations.
2647Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2648 DeclSpec &DS,
2649 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002650 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002651 TagDecl *Tag = 0;
2652 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2653 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00002654 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002655 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002656 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002657 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002658
2659 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002660 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002661
John McCall07e91c02009-08-06 02:15:43 +00002662 // Note that the above type specs guarantee that the
2663 // type rep is a Decl, whereas in many of the others
2664 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00002665 if (isa<TagDecl>(TagD))
2666 Tag = cast<TagDecl>(TagD);
2667 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2668 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002669 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002670
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00002671 if (Tag) {
David Blaikie095deba2012-11-14 01:52:05 +00002672 getASTContext().addUnnamedTag(Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00002673 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00002674 if (Tag->isInvalidDecl())
2675 return Tag;
2676 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00002677
Nuno Lopese9823fa2009-12-17 11:35:26 +00002678 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2679 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2680 // or incomplete types shall not be restrict-qualified."
2681 if (TypeQuals & DeclSpec::TQ_restrict)
2682 Diag(DS.getRestrictSpecLoc(),
2683 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2684 << DS.getSourceRange();
2685 }
2686
Richard Smitha77a0a62011-08-15 21:04:07 +00002687 if (DS.isConstexprSpecified()) {
2688 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2689 // and definitions of functions and variables.
2690 if (Tag)
2691 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2692 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2693 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00002694 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
2695 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00002696 else
2697 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2698 // Don't emit warnings after this error.
2699 return TagD;
2700 }
2701
Douglas Gregor3dad8422009-09-26 06:47:28 +00002702 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002703 // If we're dealing with a decl but not a TagDecl, assume that
2704 // whatever routines created it handled the friendship aspect.
2705 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002706 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002707 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002708 }
John McCallaa017372011-03-22 23:00:04 +00002709
2710 // Track whether we warned about the fact that there aren't any
2711 // declarators.
2712 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002713
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002714 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00002715 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002716 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002717 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002718 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002719 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002720
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002721 Diag(DS.getLocStart(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002722 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002723 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002724 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002725 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002726
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002727 // Check for Microsoft C extension: anonymous struct.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002728 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002729 CurContext->isRecord() &&
2730 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2731 // Handle 2 kinds of anonymous struct:
2732 // struct STRUCT;
2733 // and
2734 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2735 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00002736 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002737 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2738 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002739 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002740 << DS.getSourceRange();
2741 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2742 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002743 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002744
David Blaikiebbafb8a2012-03-11 07:00:24 +00002745 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002746 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2747 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2748 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002749 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002750 Diag(Enum->getLocation(), diag::ext_no_declarators)
2751 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002752 emittedWarning = true;
2753 }
2754
2755 // Skip all the checks below if we have a type error.
2756 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002757
John McCallaa017372011-03-22 23:00:04 +00002758 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002759 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002760 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002761 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2762 Tag && isa<EnumDecl>(Tag)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002763 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002764 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002765 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002766 }
2767
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002768 Diag(DS.getLocStart(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002769 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002770 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002771 }
Mike Stump11289f42009-09-09 15:08:12 +00002772
John McCallaa017372011-03-22 23:00:04 +00002773 // We're going to complain about a bunch of spurious specifiers;
2774 // only do this if we're declaring a tag, because otherwise we
2775 // should be getting diag::ext_no_declarators.
2776 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2777 return TagD;
2778
John McCall4d55f5a2011-03-26 02:09:52 +00002779 // Note that a linkage-specification sets a storage class, but
2780 // 'extern "C" struct foo;' is actually valid and not theoretically
2781 // useless.
John McCallaa017372011-03-22 23:00:04 +00002782 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002783 if (!DS.isExternInLinkageSpec())
2784 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2785 << DeclSpec::getSpecifierName(scs);
2786
John McCallaa017372011-03-22 23:00:04 +00002787 if (DS.isThreadSpecified())
2788 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2789 if (DS.getTypeQualifiers()) {
2790 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2791 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2792 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2793 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2794 // Restrict is covered above.
2795 }
2796 if (DS.isInlineSpecified())
2797 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2798 if (DS.isVirtualSpecified())
2799 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2800 if (DS.isExplicitSpecified())
2801 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2802
Douglas Gregor41866812011-09-12 18:37:38 +00002803 if (DS.isModulePrivateSpecified() &&
2804 Tag && Tag->getDeclContext()->isFunctionOrMethod())
2805 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2806 << Tag->getTagKind()
2807 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2808
Eli Friedmane3217952011-12-17 00:36:09 +00002809 // Warn about ignored type attributes, for example:
2810 // __attribute__((aligned)) struct A;
2811 // Attributes should be placed after tag to apply to type declaration.
2812 if (!DS.getAttributes().empty()) {
2813 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2814 if (TypeSpecType == DeclSpec::TST_class ||
2815 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00002816 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00002817 TypeSpecType == DeclSpec::TST_union ||
2818 TypeSpecType == DeclSpec::TST_enum) {
2819 AttributeList* attrs = DS.getAttributes().getList();
2820 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00002821 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00002822 << attrs->getName()
2823 << (TypeSpecType == DeclSpec::TST_class ? 0 :
2824 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00002825 TypeSpecType == DeclSpec::TST_union ? 2 :
2826 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00002827 attrs = attrs->getNext();
2828 }
2829 }
2830 }
John McCallaa017372011-03-22 23:00:04 +00002831
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00002832 ActOnDocumentableDecl(TagD);
2833
John McCall48871652010-08-21 09:40:31 +00002834 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002835}
2836
John McCallea305ed2009-12-18 10:40:03 +00002837/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002838/// check if there's an existing declaration that can't be overloaded.
2839///
2840/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002841static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2842 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002843 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002844 DeclarationName Name,
2845 SourceLocation NameLoc,
2846 unsigned diagnostic) {
2847 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2848 Sema::ForRedeclaration);
2849 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002850
John McCallea305ed2009-12-18 10:40:03 +00002851 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002852 return false;
2853
2854 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002855 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002856 assert(PrevDecl && "Expected a non-null Decl");
2857
2858 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2859 return false;
John McCall1f82f242009-11-18 22:49:29 +00002860
John McCallea305ed2009-12-18 10:40:03 +00002861 SemaRef.Diag(NameLoc, diagnostic) << Name;
2862 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002863
2864 return true;
2865}
2866
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002867/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2868/// anonymous struct or union AnonRecord into the owning context Owner
2869/// and scope S. This routine will be invoked just after we realize
2870/// that an unnamed union or struct is actually an anonymous union or
2871/// struct, e.g.,
2872///
2873/// @code
2874/// union {
2875/// int i;
2876/// float f;
2877/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2878/// // f into the surrounding scope.x
2879/// @endcode
2880///
2881/// This routine is recursive, injecting the names of nested anonymous
2882/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002883static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2884 DeclContext *Owner,
2885 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002886 AccessSpecifier AS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002887 SmallVector<NamedDecl*, 2> &Chaining,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002888 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002889 unsigned diagKind
2890 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2891 : diag::err_anonymous_struct_member_redecl;
2892
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002893 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002894
2895 // Look every FieldDecl and IndirectFieldDecl with a name.
2896 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2897 DEnd = AnonRecord->decls_end();
2898 D != DEnd; ++D) {
2899 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2900 cast<NamedDecl>(*D)->getDeclName()) {
2901 ValueDecl *VD = cast<ValueDecl>(*D);
2902 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2903 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002904 // C++ [class.union]p2:
2905 // The names of the members of an anonymous union shall be
2906 // distinct from the names of any other entity in the
2907 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002908 Invalid = true;
2909 } else {
2910 // C++ [class.union]p2:
2911 // For the purpose of name lookup, after the anonymous union
2912 // definition, the members of the anonymous union are
2913 // considered to have been defined in the scope in which the
2914 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002915 unsigned OldChainingSize = Chaining.size();
2916 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2917 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2918 PE = IF->chain_end(); PI != PE; ++PI)
2919 Chaining.push_back(*PI);
2920 else
2921 Chaining.push_back(VD);
2922
Francois Pichet783dd6e2010-11-21 06:08:52 +00002923 assert(Chaining.size() >= 2);
2924 NamedDecl **NamedChain =
2925 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2926 for (unsigned i = 0; i < Chaining.size(); i++)
2927 NamedChain[i] = Chaining[i];
2928
2929 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002930 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2931 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002932 NamedChain, Chaining.size());
2933
2934 IndirectField->setAccess(AS);
2935 IndirectField->setImplicit();
2936 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002937
2938 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002939 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002940
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002941 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002942 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002943 }
2944 }
2945
2946 return Invalid;
2947}
2948
Douglas Gregorc4df4072010-04-19 22:54:31 +00002949/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2950/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002951/// illegal input values are mapped to SC_None.
2952static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002953StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002954 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002955 case DeclSpec::SCS_unspecified: return SC_None;
2956 case DeclSpec::SCS_extern: return SC_Extern;
2957 case DeclSpec::SCS_static: return SC_Static;
2958 case DeclSpec::SCS_auto: return SC_Auto;
2959 case DeclSpec::SCS_register: return SC_Register;
2960 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002961 // Illegal SCSs map to None: error reporting is up to the caller.
2962 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002963 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002964 }
2965 llvm_unreachable("unknown storage class specifier");
2966}
2967
2968/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002969/// a StorageClass. Any error reporting is up to the caller:
2970/// illegal input values are mapped to SC_None.
2971static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002972StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002973 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002974 case DeclSpec::SCS_unspecified: return SC_None;
2975 case DeclSpec::SCS_extern: return SC_Extern;
2976 case DeclSpec::SCS_static: return SC_Static;
2977 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002978 // Illegal SCSs map to None: error reporting is up to the caller.
2979 case DeclSpec::SCS_auto: // Fall through.
2980 case DeclSpec::SCS_mutable: // Fall through.
2981 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002982 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002983 }
2984 llvm_unreachable("unknown storage class specifier");
2985}
2986
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002987/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002988/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002989/// (C++ [class.union]) and a C11 feature; anonymous structures
2990/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002991Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2992 AccessSpecifier AS,
2993 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002994 DeclContext *Owner = Record->getDeclContext();
2995
2996 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002997 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002998 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002999 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003000 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003001 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003002 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003003
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003004 // C and C++ require different kinds of checks for anonymous
3005 // structs/unions.
3006 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003007 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003008 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003009 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003010 if (Record->isUnion()) {
3011 // C++ [class.union]p6:
3012 // Anonymous unions declared in a named namespace or in the
3013 // global namespace shall be declared static.
3014 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3015 (isa<TranslationUnitDecl>(Owner) ||
3016 (isa<NamespaceDecl>(Owner) &&
3017 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003018 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3019 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003020
3021 // Recover by adding 'static'.
3022 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3023 PrevSpec, DiagID);
3024 }
3025 // C++ [class.union]p6:
3026 // A storage class is not allowed in a declaration of an
3027 // anonymous union in a class scope.
3028 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3029 isa<RecordDecl>(Owner)) {
3030 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003031 diag::err_anonymous_union_with_storage_spec)
3032 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003033
3034 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003035 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3036 SourceLocation(),
David Blaikie0a8e8992011-10-19 22:43:29 +00003037 PrevSpec, DiagID);
3038 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003039 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003040
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003041 // Ignore const/volatile/restrict qualifiers.
3042 if (DS.getTypeQualifiers()) {
3043 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3044 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3045 << Record->isUnion() << 0
3046 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3047 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
David Blaikie30d15442011-10-19 22:56:21 +00003048 Diag(DS.getVolatileSpecLoc(),
3049 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003050 << Record->isUnion() << 1
3051 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3052 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
David Blaikie30d15442011-10-19 22:56:21 +00003053 Diag(DS.getRestrictSpecLoc(),
3054 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003055 << Record->isUnion() << 2
3056 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3057
3058 DS.ClearTypeQualifiers();
3059 }
3060
Mike Stump11289f42009-09-09 15:08:12 +00003061 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003062 // The member-specification of an anonymous union shall only
3063 // define non-static data members. [Note: nested types and
3064 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003065 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3066 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003067 Mem != MemEnd; ++Mem) {
3068 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3069 // C++ [class.union]p3:
3070 // An anonymous union shall not have private or protected
3071 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003072 assert(FD->getAccess() != AS_none);
3073 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003074 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3075 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3076 Invalid = true;
3077 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003078
Alexis Hunt97ab5542011-05-16 22:41:40 +00003079 // C++ [class.union]p1
3080 // An object of a class with a non-trivial constructor, a non-trivial
3081 // copy constructor, a non-trivial destructor, or a non-trivial copy
3082 // assignment operator cannot be a member of a union, nor can an
3083 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003084 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003085 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003086 } else if ((*Mem)->isImplicit()) {
3087 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003088 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3089 // This is a type that showed up in an
3090 // elaborated-type-specifier inside the anonymous struct or
3091 // union, but which actually declares a type outside of the
3092 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003093 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3094 if (!MemRecord->isAnonymousStructOrUnion() &&
3095 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003096 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003097 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003098 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3099 << (int)Record->isUnion();
3100 else {
3101 // This is a nested type declaration.
3102 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3103 << (int)Record->isUnion();
3104 Invalid = true;
3105 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003106 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003107 } else if (isa<AccessSpecDecl>(*Mem)) {
3108 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003109 } else {
3110 // We have something that isn't a non-static data
3111 // member. Complain about it.
3112 unsigned DK = diag::err_anonymous_record_bad_member;
3113 if (isa<TypeDecl>(*Mem))
3114 DK = diag::err_anonymous_record_with_type;
3115 else if (isa<FunctionDecl>(*Mem))
3116 DK = diag::err_anonymous_record_with_function;
3117 else if (isa<VarDecl>(*Mem))
3118 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003119
3120 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003121 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003122 DK == diag::err_anonymous_record_with_type)
3123 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003124 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003125 else {
3126 Diag((*Mem)->getLocation(), DK)
3127 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003128 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003129 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003130 }
3131 }
Mike Stump11289f42009-09-09 15:08:12 +00003132 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003133
3134 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003135 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003136 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003137 Invalid = true;
3138 }
3139
John McCallfa2d6922009-10-22 23:31:08 +00003140 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003141 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003142 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003143 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003144
Mike Stump11289f42009-09-09 15:08:12 +00003145 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003146 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003147 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003148 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003149 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003150 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003151 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003152 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003153 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003154 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003155 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003156 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003157 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003158 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003159 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003160 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3161 assert(SCSpec != DeclSpec::SCS_typedef &&
3162 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003163 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003164 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003165 // mutable can only appear on non-static class members, so it's always
3166 // an error here
3167 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3168 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003169 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003170 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003171 SCSpec = DS.getStorageClassSpecAsWritten();
3172 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003173 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003174
Abramo Bagnaradff19302011-03-08 08:55:46 +00003175 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003176 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003177 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003178 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003179 TInfo, SC, SCAsWritten);
Richard Smith40372352011-09-18 00:06:34 +00003180
3181 // Default-initialize the implicit variable. This initialization will be
3182 // trivial in almost all cases, except if a union member has an in-class
3183 // initializer:
3184 // union { int n = 0; };
3185 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003186 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003187 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003188
3189 // Add the anonymous struct/union object to the current
3190 // context. We'll be referencing this object when we refer to one of
3191 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003192 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00003193
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003194 // Inject the members of the anonymous struct/union into the owning
3195 // context and into the identifier resolver chain for name lookup
3196 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003197 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003198 Chain.push_back(Anon);
3199
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003200 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3201 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003202 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003203
3204 // Mark this as an anonymous struct/union type. Note that we do not
3205 // do this until after we have already checked and injected the
3206 // members of this anonymous struct/union type, because otherwise
3207 // the members could be injected twice: once by DeclContext when it
3208 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00003209 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003210 Record->setAnonymousStructOrUnion(true);
3211
3212 if (Invalid)
3213 Anon->setInvalidDecl();
3214
John McCall48871652010-08-21 09:40:31 +00003215 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003216}
3217
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003218/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3219/// Microsoft C anonymous structure.
3220/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3221/// Example:
3222///
3223/// struct A { int a; };
3224/// struct B { struct A; int b; };
3225///
3226/// void foo() {
3227/// B var;
3228/// var.a = 3;
3229/// }
3230///
3231Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3232 RecordDecl *Record) {
3233
3234 // If there is no Record, get the record via the typedef.
3235 if (!Record)
3236 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3237
3238 // Mock up a declarator.
3239 Declarator Dc(DS, Declarator::TypeNameContext);
3240 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3241 assert(TInfo && "couldn't build declarator info for anonymous struct");
3242
3243 // Create a declaration for this anonymous struct.
3244 NamedDecl* Anon = FieldDecl::Create(Context,
3245 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003246 DS.getLocStart(),
3247 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003248 /*IdentifierInfo=*/0,
3249 Context.getTypeDeclType(Record),
3250 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003251 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003252 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003253 Anon->setImplicit();
3254
3255 // Add the anonymous struct object to the current context.
3256 CurContext->addDecl(Anon);
3257
3258 // Inject the members of the anonymous struct into the current
3259 // context and into the identifier resolver chain for name lookup
3260 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003261 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003262 Chain.push_back(Anon);
3263
Nico Weberf8bb3de2012-02-01 00:41:00 +00003264 RecordDecl *RecordDef = Record->getDefinition();
3265 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3266 RecordDef, AS_none,
3267 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003268 Anon->setInvalidDecl();
3269
3270 return Anon;
3271}
Steve Naroff2fea1392007-09-02 02:04:30 +00003272
Douglas Gregor92751d42008-11-17 22:58:34 +00003273/// GetNameForDeclarator - Determine the full declaration name for the
3274/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003275DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003276 return GetNameFromUnqualifiedId(D.getName());
3277}
3278
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003279/// \brief Retrieves the declaration name from a parsed unqualified-id.
3280DeclarationNameInfo
3281Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3282 DeclarationNameInfo NameInfo;
3283 NameInfo.setLoc(Name.StartLocation);
3284
Douglas Gregor7861a802009-11-03 01:35:08 +00003285 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003286
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003287 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003288 case UnqualifiedId::IK_Identifier:
3289 NameInfo.setName(Name.Identifier);
3290 NameInfo.setLoc(Name.StartLocation);
3291 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003292
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003293 case UnqualifiedId::IK_OperatorFunctionId:
3294 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3295 Name.OperatorFunctionId.Operator));
3296 NameInfo.setLoc(Name.StartLocation);
3297 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3298 = Name.OperatorFunctionId.SymbolLocations[0];
3299 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3300 = Name.EndLocation.getRawEncoding();
3301 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003302
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003303 case UnqualifiedId::IK_LiteralOperatorId:
3304 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3305 Name.Identifier));
3306 NameInfo.setLoc(Name.StartLocation);
3307 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3308 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003309
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003310 case UnqualifiedId::IK_ConversionFunctionId: {
3311 TypeSourceInfo *TInfo;
3312 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3313 if (Ty.isNull())
3314 return DeclarationNameInfo();
3315 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3316 Context.getCanonicalType(Ty)));
3317 NameInfo.setLoc(Name.StartLocation);
3318 NameInfo.setNamedTypeInfo(TInfo);
3319 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003320 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003321
3322 case UnqualifiedId::IK_ConstructorName: {
3323 TypeSourceInfo *TInfo;
3324 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3325 if (Ty.isNull())
3326 return DeclarationNameInfo();
3327 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3328 Context.getCanonicalType(Ty)));
3329 NameInfo.setLoc(Name.StartLocation);
3330 NameInfo.setNamedTypeInfo(TInfo);
3331 return NameInfo;
3332 }
3333
3334 case UnqualifiedId::IK_ConstructorTemplateId: {
3335 // In well-formed code, we can only have a constructor
3336 // template-id that refers to the current context, so go there
3337 // to find the actual type being constructed.
3338 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3339 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3340 return DeclarationNameInfo();
3341
3342 // Determine the type of the class being constructed.
3343 QualType CurClassType = Context.getTypeDeclType(CurClass);
3344
3345 // FIXME: Check two things: that the template-id names the same type as
3346 // CurClassType, and that the template-id does not occur when the name
3347 // was qualified.
3348
3349 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3350 Context.getCanonicalType(CurClassType)));
3351 NameInfo.setLoc(Name.StartLocation);
3352 // FIXME: should we retrieve TypeSourceInfo?
3353 NameInfo.setNamedTypeInfo(0);
3354 return NameInfo;
3355 }
3356
3357 case UnqualifiedId::IK_DestructorName: {
3358 TypeSourceInfo *TInfo;
3359 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3360 if (Ty.isNull())
3361 return DeclarationNameInfo();
3362 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3363 Context.getCanonicalType(Ty)));
3364 NameInfo.setLoc(Name.StartLocation);
3365 NameInfo.setNamedTypeInfo(TInfo);
3366 return NameInfo;
3367 }
3368
3369 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003370 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003371 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3372 return Context.getNameForTemplate(TName, TNameLoc);
3373 }
3374
3375 } // switch (Name.getKind())
3376
David Blaikie83d382b2011-09-23 05:06:16 +00003377 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003378}
3379
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003380static QualType getCoreType(QualType Ty) {
3381 do {
3382 if (Ty->isPointerType() || Ty->isReferenceType())
3383 Ty = Ty->getPointeeType();
3384 else if (Ty->isArrayType())
3385 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3386 else
3387 return Ty.withoutLocalFastQualifiers();
3388 } while (true);
3389}
3390
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003391/// hasSimilarParameters - Determine whether the C++ functions Declaration
3392/// and Definition have "nearly" matching parameters. This heuristic is
3393/// used to improve diagnostics in the case where an out-of-line function
3394/// definition doesn't match any declaration within the class or namespace.
3395/// Also sets Params to the list of indices to the parameters that differ
3396/// between the declaration and the definition. If hasSimilarParameters
3397/// returns true and Params is empty, then all of the parameters match.
3398static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003399 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003400 FunctionDecl *Definition,
3401 llvm::SmallVectorImpl<unsigned> &Params) {
3402 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003403 if (Declaration->param_size() != Definition->param_size())
3404 return false;
3405 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3406 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3407 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3408
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003409 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003410 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003411 continue;
3412
3413 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3414 QualType DefParamBaseTy = getCoreType(DefParamTy);
3415 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3416 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3417
3418 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3419 (DeclTyName && DeclTyName == DefTyName))
3420 Params.push_back(Idx);
3421 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00003422 return false;
3423 }
3424
3425 return true;
3426}
3427
John McCall99b2fe52010-04-29 23:50:39 +00003428/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3429/// declarator needs to be rebuilt in the current instantiation.
3430/// Any bits of declarator which appear before the name are valid for
3431/// consideration here. That's specifically the type in the decl spec
3432/// and the base type in any member-pointer chunks.
3433static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3434 DeclarationName Name) {
3435 // The types we specifically need to rebuild are:
3436 // - typenames, typeofs, and decltypes
3437 // - types which will become injected class names
3438 // Of course, we also need to rebuild any type referencing such a
3439 // type. It's safest to just say "dependent", but we call out a
3440 // few cases here.
3441
3442 DeclSpec &DS = D.getMutableDeclSpec();
3443 switch (DS.getTypeSpecType()) {
3444 case DeclSpec::TST_typename:
3445 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00003446 case DeclSpec::TST_underlyingType:
3447 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00003448 // Grab the type from the parser.
3449 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00003450 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00003451 if (T.isNull() || !T->isDependentType()) break;
3452
3453 // Make sure there's a type source info. This isn't really much
3454 // of a waste; most dependent types should have type source info
3455 // attached already.
3456 if (!TSI)
3457 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3458
3459 // Rebuild the type in the current instantiation.
3460 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3461 if (!TSI) return true;
3462
3463 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00003464 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3465 DS.UpdateTypeRep(LocType);
3466 break;
3467 }
3468
Richard Smith1620ebd2012-10-01 20:35:07 +00003469 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00003470 case DeclSpec::TST_typeofExpr: {
3471 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00003472 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00003473 if (Result.isInvalid()) return true;
3474 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00003475 break;
3476 }
3477
3478 default:
3479 // Nothing to do for these decl specs.
3480 break;
3481 }
3482
3483 // It doesn't matter what order we do this in.
3484 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3485 DeclaratorChunk &Chunk = D.getTypeObject(I);
3486
3487 // The only type information in the declarator which can come
3488 // before the declaration name is the base type of a member
3489 // pointer.
3490 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3491 continue;
3492
3493 // Rebuild the scope specifier in-place.
3494 CXXScopeSpec &SS = Chunk.Mem.Scope();
3495 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3496 return true;
3497 }
3498
3499 return false;
3500}
3501
Anders Carlsson1052fd72011-07-04 16:28:17 +00003502Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00003503 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003504 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003505
3506 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00003507 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003508 Dcl->setTopLevelDeclInObjCContainer();
3509
3510 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00003511}
3512
Richard Smithdda56e42011-04-15 14:24:37 +00003513/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3514/// If T is the name of a class, then each of the following shall have a
3515/// name different from T:
3516/// - every static data member of class T;
3517/// - every member function of class T
3518/// - every member of class T that is itself a type;
3519/// \returns true if the declaration name violates these rules.
3520bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3521 DeclarationNameInfo NameInfo) {
3522 DeclarationName Name = NameInfo.getName();
3523
3524 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3525 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3526 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3527 return true;
3528 }
3529
3530 return false;
3531}
Douglas Gregor31feb332012-03-17 23:06:31 +00003532
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003533/// \brief Diagnose a declaration whose declarator-id has the given
3534/// nested-name-specifier.
3535///
3536/// \param SS The nested-name-specifier of the declarator-id.
3537///
3538/// \param DC The declaration context to which the nested-name-specifier
3539/// resolves.
3540///
3541/// \param Name The name of the entity being declared.
3542///
3543/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00003544///
3545/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003546bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00003547 DeclarationName Name,
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003548 SourceLocation Loc) {
3549 DeclContext *Cur = CurContext;
3550 while (isa<LinkageSpecDecl>(Cur))
3551 Cur = Cur->getParent();
3552
3553 // C++ [dcl.meaning]p1:
3554 // A declarator-id shall not be qualified except for the definition
3555 // of a member function (9.3) or static data member (9.4) outside of
3556 // its class, the definition or explicit instantiation of a function
3557 // or variable member of a namespace outside of its namespace, or the
3558 // definition of an explicit specialization outside of its namespace,
3559 // or the declaration of a friend function that is a member of
3560 // another class or namespace (11.3). [...]
3561
3562 // The user provided a superfluous scope specifier that refers back to the
3563 // class or namespaces in which the entity is already declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00003564 //
3565 // class X {
3566 // void X::f();
3567 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003568 if (Cur->Equals(DC)) {
Douglas Gregor43bc0362012-09-13 20:16:20 +00003569 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
3570 : diag::err_member_extra_qualification)
Douglas Gregor31feb332012-03-17 23:06:31 +00003571 << Name << FixItHint::CreateRemoval(SS.getRange());
3572 SS.clear();
3573 return false;
3574 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003575
3576 // Check whether the qualifying scope encloses the scope of the original
3577 // declaration.
3578 if (!Cur->Encloses(DC)) {
3579 if (Cur->isRecord())
3580 Diag(Loc, diag::err_member_qualification)
3581 << Name << SS.getRange();
3582 else if (isa<TranslationUnitDecl>(DC))
3583 Diag(Loc, diag::err_invalid_declarator_global_scope)
3584 << Name << SS.getRange();
3585 else if (isa<FunctionDecl>(Cur))
3586 Diag(Loc, diag::err_invalid_declarator_in_function)
3587 << Name << SS.getRange();
3588 else
3589 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00003590 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003591
Douglas Gregor31feb332012-03-17 23:06:31 +00003592 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003593 }
3594
3595 if (Cur->isRecord()) {
3596 // Cannot qualify members within a class.
3597 Diag(Loc, diag::err_member_qualification)
3598 << Name << SS.getRange();
3599 SS.clear();
3600
3601 // C++ constructors and destructors with incorrect scopes can break
3602 // our AST invariants by having the wrong underlying types. If
3603 // that's the case, then drop this declaration entirely.
3604 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3605 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3606 !Context.hasSameType(Name.getCXXNameType(),
3607 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3608 return true;
3609
3610 return false;
3611 }
Douglas Gregor31feb332012-03-17 23:06:31 +00003612
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003613 // C++11 [dcl.meaning]p1:
3614 // [...] "The nested-name-specifier of the qualified declarator-id shall
3615 // not begin with a decltype-specifer"
3616 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3617 while (SpecLoc.getPrefix())
3618 SpecLoc = SpecLoc.getPrefix();
3619 if (dyn_cast_or_null<DecltypeType>(
3620 SpecLoc.getNestedNameSpecifier()->getAsType()))
3621 Diag(Loc, diag::err_decltype_in_declarator)
3622 << SpecLoc.getTypeLoc().getSourceRange();
3623
Douglas Gregor31feb332012-03-17 23:06:31 +00003624 return false;
3625}
3626
John McCall48871652010-08-21 09:40:31 +00003627Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003628 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003629 // TODO: consider using NameInfo for diagnostic.
3630 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3631 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00003632
Chris Lattner02c04392007-07-25 00:24:17 +00003633 // All of these full declarators require an identifier. If it doesn't have
3634 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00003635 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003636 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003637 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003638 diag::err_declarator_need_ident)
3639 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00003640 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00003641 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3642 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003643
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003644 // The scope passed in may not be a decl scope. Zip up the scope tree until
3645 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00003646 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003647 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003648 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003649
John McCall99b2fe52010-04-29 23:50:39 +00003650 DeclContext *DC = CurContext;
3651 if (D.getCXXScopeSpec().isInvalid())
3652 D.setInvalidType();
3653 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003654 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3655 UPPC_DeclarationQualifier))
3656 return 0;
3657
John McCall99b2fe52010-04-29 23:50:39 +00003658 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3659 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3660 if (!DC) {
3661 // If we could not compute the declaration context, it's because the
3662 // declaration context is dependent but does not refer to a class,
3663 // class template, or class template partial specialization. Complain
3664 // and return early, to avoid the coming semantic disaster.
3665 Diag(D.getIdentifierLoc(),
3666 diag::err_template_qualified_declarator_no_match)
3667 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3668 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003669 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003670 }
John McCall99b2fe52010-04-29 23:50:39 +00003671 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003672
John McCall99b2fe52010-04-29 23:50:39 +00003673 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003674 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003675 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003676
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003677 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3678 Diag(D.getIdentifierLoc(),
3679 diag::err_member_def_undefined_record)
3680 << Name << DC << D.getCXXScopeSpec().getRange();
3681 D.setInvalidType();
3682 } else if (!D.getDeclSpec().isFriendSpecified()) {
3683 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3684 Name, D.getIdentifierLoc())) {
3685 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00003686 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003687
3688 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00003689 }
John McCall99b2fe52010-04-29 23:50:39 +00003690 }
3691
3692 // Check whether we need to rebuild the type of the given
3693 // declaration in the current instantiation.
3694 if (EnteringContext && IsDependentContext &&
3695 TemplateParamLists.size() != 0) {
3696 ContextRAII SavedContext(*this, DC);
3697 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3698 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003699 }
3700 }
Richard Smithdda56e42011-04-15 14:24:37 +00003701
3702 if (DiagnoseClassNameShadow(DC, NameInfo))
3703 // If this is a typedef, we'll end up spewing multiple diagnostics.
3704 // Just return early; it's safer.
3705 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3706 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003707
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003708 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003709
John McCall8cb7bdf2010-06-04 23:28:52 +00003710 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3711 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003712
Douglas Gregor506bd562010-12-13 22:49:22 +00003713 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3714 UPPC_DeclarationType))
3715 D.setInvalidType();
3716
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003717 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003718 ForRedeclaration);
3719
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003720 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003721 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003722 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003723
3724 // If the declaration we're planning to build will be a function
3725 // or object with linkage, then look for another declaration with
3726 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3727 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3728 /* Do nothing*/;
3729 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003730 if (CurContext->isFunctionOrMethod() ||
3731 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003732 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003733 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003734 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003735 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003736 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003737 IsLinkageLookup = true;
3738
3739 if (IsLinkageLookup)
3740 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003741
John McCall1f82f242009-11-18 22:49:29 +00003742 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003743 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003744 LookupQualifiedName(Previous, DC);
3745
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003746 // C++ [dcl.meaning]p1:
3747 // When the declarator-id is qualified, the declaration shall refer to a
3748 // previously declared member of the class or namespace to which the
3749 // qualifier refers (or, in the case of a namespace, of an element of the
3750 // inline namespace set of that namespace (7.3.1)) or to a specialization
3751 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003752 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003753 // Note that we already checked the context above, and that we do not have
3754 // enough information to make sure that Previous contains the declaration
3755 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00003756 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003757 // class X {
3758 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003759 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003760 // };
3761 //
Douglas Gregorad590502008-12-15 23:53:10 +00003762 // void X::f(int) { } // ill-formed
3763 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003764 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00003765 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003766 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003767
3768 // C++ [dcl.meaning]p1:
3769 // [...] the member shall not merely have been introduced by a
3770 // using-declaration in the scope of the class or namespace nominated by
3771 // the nested-name-specifier of the declarator-id.
3772 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003773 }
3774
John McCall1f82f242009-11-18 22:49:29 +00003775 if (Previous.isSingleResult() &&
3776 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003777 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003778 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00003779 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3780 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003781
Douglas Gregor5101c242008-12-05 18:15:24 +00003782 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003783 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003784 }
3785
Douglas Gregor83a586e2008-04-13 21:07:44 +00003786 // In C++, the previous declaration we find might be a tag type
3787 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003788 // tag type. Note that this does does not apply if we're declaring a
3789 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003790 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003791 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003792 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003793
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003794 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00003795 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003796 if (TemplateParamLists.size()) {
3797 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003798 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003799 }
Mike Stump11289f42009-09-09 15:08:12 +00003800
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003801 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003802 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003803 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003804 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003805 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00003806 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003807 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003808 TemplateParamLists);
Chris Lattner01a7c532007-01-25 23:09:03 +00003809 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003810
3811 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003812 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003813
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003814 // If this has an identifier and is not an invalid redeclaration or
3815 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003816 if (New->getDeclName() && AddToScope &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003817 !(D.isRedeclaration() && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003818 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003819
John McCall48871652010-08-21 09:40:31 +00003820 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003821}
3822
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00003823/// Helper method to turn variable array types into constant array
3824/// types in certain situations which would otherwise be errors (for
3825/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00003826static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3827 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003828 bool &SizeIsNegative,
3829 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003830 // This method tries to turn a variable array into a constant
3831 // array even when the size isn't an ICE. This is necessary
3832 // for compatibility with code that depends on gcc's buggy
3833 // constant expression folding, like struct {char x[(int)(char*)2];}
3834 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003835 Oversized = 0;
3836
3837 if (T->isDependentType())
3838 return QualType();
3839
John McCall8ccfcb52009-09-24 19:53:00 +00003840 QualifierCollector Qs;
3841 const Type *Ty = Qs.strip(T);
3842
3843 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003844 QualType Pointee = PTy->getPointeeType();
3845 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003846 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3847 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003848 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003849 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003850 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003851 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003852 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3853 QualType Inner = PTy->getInnerType();
3854 QualType FixedType =
3855 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3856 Oversized);
3857 if (FixedType.isNull()) return FixedType;
3858 FixedType = Context.getParenType(FixedType);
3859 return Qs.apply(Context, FixedType);
3860 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003861
3862 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003863 if (!VLATy)
3864 return QualType();
3865 // FIXME: We should probably handle this case
3866 if (VLATy->getElementType()->isVariablyModifiedType())
3867 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003868
Richard Smith42d3af92011-12-07 00:43:50 +00003869 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003870 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00003871 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00003872 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003873
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003874 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003875 if (Res.isSigned() && Res.isNegative()) {
3876 SizeIsNegative = true;
3877 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003878 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003879
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003880 // Check whether the array is too large to be addressed.
3881 unsigned ActiveSizeBits
3882 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3883 Res);
3884 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3885 Oversized = Res;
3886 return QualType();
3887 }
3888
3889 return Context.getConstantArrayType(VLATy->getElementType(),
3890 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003891}
3892
Abramo Bagnara341ab732012-11-08 14:44:42 +00003893static void
3894FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
3895 if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) {
3896 PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL);
3897 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(),
3898 DstPTL->getPointeeLoc());
3899 DstPTL->setStarLoc(SrcPTL->getStarLoc());
3900 return;
3901 }
3902 if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) {
3903 ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL);
3904 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(),
3905 DstPTL->getInnerLoc());
3906 DstPTL->setLParenLoc(SrcPTL->getLParenLoc());
3907 DstPTL->setRParenLoc(SrcPTL->getRParenLoc());
3908 return;
3909 }
3910 ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL);
3911 ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL);
3912 TypeLoc SrcElemTL = SrcATL->getElementLoc();
3913 TypeLoc DstElemTL = DstATL->getElementLoc();
3914 DstElemTL.initializeFullCopy(SrcElemTL);
3915 DstATL->setLBracketLoc(SrcATL->getLBracketLoc());
3916 DstATL->setSizeExpr(SrcATL->getSizeExpr());
3917 DstATL->setRBracketLoc(SrcATL->getRBracketLoc());
3918}
3919
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00003920/// Helper method to turn variable array types into constant array
3921/// types in certain situations which would otherwise be errors (for
3922/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00003923static TypeSourceInfo*
3924TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
3925 ASTContext &Context,
3926 bool &SizeIsNegative,
3927 llvm::APSInt &Oversized) {
3928 QualType FixedTy
3929 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
3930 SizeIsNegative, Oversized);
3931 if (FixedTy.isNull())
3932 return 0;
3933 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
3934 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
3935 FixedTInfo->getTypeLoc());
3936 return FixedTInfo;
3937}
3938
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003939/// \brief Register the given locally-scoped external C declaration so
3940/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003941void
John McCall1f82f242009-11-18 22:49:29 +00003942Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3943 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003944 Scope *S) {
3945 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3946 "Decl is not a locally-scoped decl!");
3947 // Note that we have a locally-scoped external with this name.
3948 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3949
John McCall1f82f242009-11-18 22:49:29 +00003950 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003951 return;
3952
John McCall1f82f242009-11-18 22:49:29 +00003953 NamedDecl *PrevDecl = Previous.getFoundDecl();
3954
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003955 // If there was a previous declaration of this variable, it may be
3956 // in our identifier chain. Update the identifier chain with the new
3957 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003958 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003959 // The previous declaration was found on the identifer resolver
3960 // chain, so remove it from its scope.
Douglas Gregor825faf72011-06-29 21:22:02 +00003961
3962 if (S->isDeclScope(PrevDecl)) {
3963 // Special case for redeclarations in the SAME scope.
3964 // Because this declaration is going to be added to the identifier chain
3965 // later, we should temporarily take it OFF the chain.
3966 IdResolver.RemoveDecl(ND);
3967
3968 } else {
3969 // Find the scope for the original declaration.
3970 while (S && !S->isDeclScope(PrevDecl))
3971 S = S->getParent();
3972 }
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003973
3974 if (S)
John McCall48871652010-08-21 09:40:31 +00003975 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003976 }
3977}
3978
Douglas Gregordc5c9582011-07-28 14:20:37 +00003979llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3980Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3981 if (ExternalSource) {
3982 // Load locally-scoped external decls from the external source.
3983 SmallVector<NamedDecl *, 4> Decls;
3984 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3985 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3986 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3987 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3988 if (Pos == LocallyScopedExternalDecls.end())
3989 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3990 }
3991 }
3992
3993 return LocallyScopedExternalDecls.find(Name);
3994}
3995
Eli Friedman574c7452009-04-07 19:37:57 +00003996/// \brief Diagnose function specifiers on a declaration of an identifier that
3997/// does not identify a function.
3998void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3999 // FIXME: We should probably indicate the identifier in question to avoid
4000 // confusion for constructs like "inline int a(), b;"
4001 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00004002 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004003 diag::err_inline_non_function);
4004
4005 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00004006 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004007 diag::err_virtual_non_function);
4008
4009 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00004010 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004011 diag::err_explicit_non_function);
4012}
4013
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004014NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004015Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004016 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004017 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4018 if (D.getCXXScopeSpec().isSet()) {
4019 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4020 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004021 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004022 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004023 DC = CurContext;
4024 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004025 }
4026
David Blaikiebbafb8a2012-03-11 07:00:24 +00004027 if (getLangOpts().CPlusPlus) {
Douglas Gregor0c880302009-03-11 23:00:04 +00004028 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004029 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00004030 }
4031
Eli Friedman574c7452009-04-07 19:37:57 +00004032 DiagnoseFunctionSpecifiers(D);
4033
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004034 if (D.getDeclSpec().isThreadSpecified())
4035 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00004036 if (D.getDeclSpec().isConstexprSpecified())
4037 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4038 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004039
Douglas Gregord8f446f2010-07-13 06:37:01 +00004040 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4041 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4042 << D.getName().getSourceRange();
4043 return 0;
4044 }
4045
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004046 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004047 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004048
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004049 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004050 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004051
Richard Smith3f1b5d02011-05-05 21:57:07 +00004052 CheckTypedefForVariablyModifiedType(S, NewTD);
4053
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004054 bool Redeclaration = D.isRedeclaration();
4055 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4056 D.setRedeclaration(Redeclaration);
4057 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004058}
4059
Richard Smith3f1b5d02011-05-05 21:57:07 +00004060void
4061Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004062 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4063 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004064 // Note that variably modified types must be fixed before merging the decl so
4065 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004066 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4067 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004068 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004069 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004070
Chris Lattner9fecd742009-04-19 05:21:20 +00004071 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004072 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004073 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004074 TypeSourceInfo *FixedTInfo =
4075 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4076 SizeIsNegative,
4077 Oversized);
4078 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004079 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004080 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004081 } else {
4082 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004083 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004084 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004085 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004086 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004087 Diag(NewTD->getLocation(), diag::err_array_too_large)
4088 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004089 else
Richard Smithdda56e42011-04-15 14:24:37 +00004090 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004091 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004092 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004093 }
4094 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004095}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004096
Richard Smith3f1b5d02011-05-05 21:57:07 +00004097
4098/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4099/// declares a typedef-name, either using the 'typedef' type specifier or via
4100/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4101NamedDecl*
4102Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4103 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004104 // Merge the decl with the existing one if appropriate. If the decl is
4105 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004106 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00004107 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004108 if (!Previous.empty()) {
4109 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004110 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004111 }
4112
Douglas Gregor27821ce2009-07-07 16:35:42 +00004113 // If this is the C FILE type, notify the AST context.
4114 if (IdentifierInfo *II = NewTD->getIdentifier())
4115 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004116 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004117 if (II->isStr("FILE"))
4118 Context.setFILEDecl(NewTD);
4119 else if (II->isStr("jmp_buf"))
4120 Context.setjmp_bufDecl(NewTD);
4121 else if (II->isStr("sigjmp_buf"))
4122 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004123 else if (II->isStr("ucontext_t"))
4124 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004125 }
4126
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004127 return NewTD;
4128}
4129
Douglas Gregor5d68a202009-02-24 19:23:27 +00004130/// \brief Determines whether the given declaration is an out-of-scope
4131/// previous declaration.
4132///
4133/// This routine should be invoked when name lookup has found a
4134/// previous declaration (PrevDecl) that is not in the scope where a
4135/// new declaration by the same name is being introduced. If the new
4136/// declaration occurs in a local scope, previous declarations with
4137/// linkage may still be considered previous declarations (C99
4138/// 6.2.2p4-5, C++ [basic.link]p6).
4139///
4140/// \param PrevDecl the previous declaration found by name
4141/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004142///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004143/// \param DC the context in which the new declaration is being
4144/// declared.
4145///
4146/// \returns true if PrevDecl is an out-of-scope previous declaration
4147/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004148static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004149isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4150 ASTContext &Context) {
4151 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004152 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004153
Douglas Gregoreddf4332009-02-24 20:03:32 +00004154 if (!PrevDecl->hasLinkage())
4155 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004156
David Blaikiebbafb8a2012-03-11 07:00:24 +00004157 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004158 // C++ [basic.link]p6:
4159 // If there is a visible declaration of an entity with linkage
4160 // having the same name and type, ignoring entities declared
4161 // outside the innermost enclosing namespace scope, the block
4162 // scope declaration declares that same entity and receives the
4163 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004164 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004165 if (!OuterContext->isFunctionOrMethod())
4166 // This rule only applies to block-scope declarations.
4167 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004168
4169 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4170 if (PrevOuterContext->isRecord())
4171 // We found a member function: ignore it.
4172 return false;
4173
4174 // Find the innermost enclosing namespace for the new and
4175 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004176 OuterContext = OuterContext->getEnclosingNamespaceContext();
4177 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004178
Douglas Gregorfcee9462010-08-27 22:55:10 +00004179 // The previous declaration is in a different namespace, so it
4180 // isn't the same function.
4181 if (!OuterContext->Equals(PrevOuterContext))
4182 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004183 }
4184
Douglas Gregor5d68a202009-02-24 19:23:27 +00004185 return true;
4186}
4187
John McCall3e11ebe2010-03-15 10:12:16 +00004188static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4189 CXXScopeSpec &SS = D.getCXXScopeSpec();
4190 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004191 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004192}
4193
John McCall31168b02011-06-15 23:02:42 +00004194bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4195 QualType type = decl->getType();
4196 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4197 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4198 // Various kinds of declaration aren't allowed to be __autoreleasing.
4199 unsigned kind = -1U;
4200 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4201 if (var->hasAttr<BlocksAttr>())
4202 kind = 0; // __block
4203 else if (!var->hasLocalStorage())
4204 kind = 1; // global
4205 } else if (isa<ObjCIvarDecl>(decl)) {
4206 kind = 3; // ivar
4207 } else if (isa<FieldDecl>(decl)) {
4208 kind = 2; // field
4209 }
4210
4211 if (kind != -1U) {
4212 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4213 << kind;
4214 }
4215 } else if (lifetime == Qualifiers::OCL_None) {
4216 // Try to infer lifetime.
4217 if (!type->isObjCLifetimeType())
4218 return false;
4219
4220 lifetime = type->getObjCARCImplicitLifetime();
4221 type = Context.getLifetimeQualifiedType(type, lifetime);
4222 decl->setType(type);
4223 }
4224
4225 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4226 // Thread-local variables cannot have lifetime.
4227 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4228 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004229 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004230 << var->getType();
4231 return true;
4232 }
4233 }
4234
4235 return false;
4236}
4237
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004238NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00004239Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004240 TypeSourceInfo *TInfo, LookupResult &Previous,
4241 MultiTemplateParamsArg TemplateParamLists) {
4242 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004243 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004244
4245 // Check that there are no default arguments (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004246 if (getLangOpts().CPlusPlus)
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004247 CheckExtraCXXDefaultArguments(D);
4248
Douglas Gregorc4df4072010-04-19 22:54:31 +00004249 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4250 assert(SCSpec != DeclSpec::SCS_typedef &&
4251 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00004252 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00004253 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004254 // mutable can only appear on non-static class members, so it's always
4255 // an error here
4256 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004257 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004258 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004259 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00004260 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4261 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00004262 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004263
4264 IdentifierInfo *II = Name.getAsIdentifierInfo();
4265 if (!II) {
4266 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00004267 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004268 return 0;
4269 }
4270
Eli Friedman574c7452009-04-07 19:37:57 +00004271 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00004272
Douglas Gregor212cab32009-03-11 20:22:50 +00004273 if (!DC->isRecord() && S->getFnParent() == 0) {
4274 // C99 6.9p2: The storage-class specifiers auto and register shall not
4275 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00004276 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00004277
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004278 // If this is a register variable with an asm label specified, then this
4279 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00004280 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004281 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4282 else
4283 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004284 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004285 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004286 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004287
David Blaikiebbafb8a2012-03-11 07:00:24 +00004288 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004289 // Set up the special work-group-local storage class for variables in the
4290 // OpenCL __local address space.
4291 if (R.getAddressSpace() == LangAS::opencl_local)
4292 SC = SC_OpenCLWorkGroupLocal;
4293 }
4294
Ted Kremenek582a0992011-01-23 17:04:59 +00004295 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004296 VarDecl *NewVD;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004297 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004298 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004299 D.getIdentifierLoc(), II,
4300 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004301
4302 if (D.isInvalidType())
4303 NewVD->setInvalidDecl();
4304 } else {
4305 if (DC->isRecord() && !CurContext->isRecord()) {
4306 // This is an out-of-line definition of a static data member.
4307 if (SC == SC_Static) {
4308 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4309 diag::err_static_out_of_line)
4310 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4311 } else if (SC == SC_None)
4312 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00004313 }
Richard Smith42973752012-02-16 20:41:22 +00004314 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004315 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4316 if (RD->isLocalClass())
4317 Diag(D.getIdentifierLoc(),
4318 diag::err_static_data_member_not_allowed_in_local_class)
4319 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004320
Richard Smith42973752012-02-16 20:41:22 +00004321 // C++98 [class.union]p1: If a union contains a static data member,
4322 // the program is ill-formed. C++11 drops this restriction.
4323 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004324 Diag(D.getIdentifierLoc(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00004325 getLangOpts().CPlusPlus0x
Richard Smith42973752012-02-16 20:41:22 +00004326 ? diag::warn_cxx98_compat_static_data_member_in_union
4327 : diag::ext_static_data_member_in_union) << Name;
4328 // We conservatively disallow static data members in anonymous structs.
4329 else if (!RD->getDeclName())
4330 Diag(D.getIdentifierLoc(),
4331 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004332 << Name << RD->isUnion();
4333 }
4334 }
4335
4336 // Match up the template parameter lists with the scope specifier, then
4337 // determine whether we have a template or a template specialization.
4338 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004339 bool Invalid = false;
4340 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004341 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004342 D.getDeclSpec().getLocStart(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004343 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004344 D.getCXXScopeSpec(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004345 TemplateParamLists.data(),
John McCallace48cd2010-10-19 01:40:49 +00004346 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00004347 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004348 isExplicitSpecialization,
4349 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004350 if (TemplateParams->size() > 0) {
4351 // There is no such thing as a variable template.
4352 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4353 << II
4354 << SourceRange(TemplateParams->getTemplateLoc(),
4355 TemplateParams->getRAngleLoc());
4356 return 0;
4357 } else {
4358 // There is an extraneous 'template<>' for this variable. Complain
4359 // about it, but allow the declaration of the variable.
4360 Diag(TemplateParams->getTemplateLoc(),
4361 diag::err_template_variable_noparams)
4362 << II
4363 << SourceRange(TemplateParams->getTemplateLoc(),
4364 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004365 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00004366 }
Mike Stump11289f42009-09-09 15:08:12 +00004367
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004368 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004369 D.getIdentifierLoc(), II,
4370 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004371
Richard Smithb2bc2e62011-02-21 20:05:19 +00004372 // If this decl has an auto type in need of deduction, make a note of the
4373 // Decl so we can diagnose uses of it in its own initializer.
4374 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4375 R->getContainedAutoType())
4376 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00004377
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004378 if (D.isInvalidType() || Invalid)
4379 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004380
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004381 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00004382
Abramo Bagnara60804e12011-03-18 15:16:37 +00004383 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004384 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00004385 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004386 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004387 }
Richard Smitha77a0a62011-08-15 21:04:07 +00004388
Richard Smith6331c402012-02-13 22:16:19 +00004389 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00004390 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004391 }
4392
Douglas Gregor41866812011-09-12 18:37:38 +00004393 // Set the lexical context. If the declarator has a C++ scope specifier, the
4394 // lexical context will be different from the semantic context.
4395 NewVD->setLexicalDeclContext(CurContext);
4396
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004397 if (D.getDeclSpec().isThreadSpecified()) {
4398 if (NewVD->hasLocalStorage())
4399 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Douglas Gregore8bbc122011-09-02 00:18:52 +00004400 else if (!Context.getTargetInfo().isTLSSupported())
Eli Friedmandaea3f62009-04-19 21:48:33 +00004401 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004402 else
4403 NewVD->setThreadSpecified(true);
4404 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004405
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00004406 if (D.getDeclSpec().isModulePrivateSpecified()) {
4407 if (isExplicitSpecialization)
4408 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4409 << 2
4410 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00004411 else if (NewVD->hasLocalStorage())
4412 Diag(NewVD->getLocation(), diag::err_module_private_local)
4413 << 0 << NewVD->getDeclName()
4414 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4415 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00004416 else
4417 NewVD->setModulePrivate();
4418 }
Douglas Gregor26701a42011-09-09 02:06:17 +00004419
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004420 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004421 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004422
Peter Collingbournec6b08572012-08-28 20:37:50 +00004423 if (getLangOpts().CUDA) {
4424 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
4425 // storage [duration]."
4426 if (SC == SC_None && S->getFnParent() != 0 &&
4427 (NewVD->hasAttr<CUDASharedAttr>() || NewVD->hasAttr<CUDAConstantAttr>()))
4428 NewVD->setStorageClass(SC_Static);
4429 }
4430
John McCall31168b02011-06-15 23:02:42 +00004431 // In auto-retain/release, infer strong retension for variables of
4432 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004433 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00004434 NewVD->setInvalidDecl();
4435
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004436 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00004437 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004438 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004439 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004440 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00004441 if (S->getFnParent() != 0) {
4442 switch (SC) {
4443 case SC_None:
4444 case SC_Auto:
4445 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4446 break;
4447 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00004448 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00004449 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4450 break;
4451 case SC_Static:
4452 case SC_Extern:
4453 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004454 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00004455 break;
4456 }
4457 }
4458
4459 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00004460 Context, Label));
David Chisnall0867d9c2012-02-18 16:12:34 +00004461 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4462 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4463 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4464 if (I != ExtnameUndeclaredIdentifiers.end()) {
4465 NewVD->addAttr(I->second);
4466 ExtnameUndeclaredIdentifiers.erase(I);
4467 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004468 }
4469
John McCalla2a3f7d2010-03-16 21:48:18 +00004470 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00004471 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00004472 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00004473
John McCall1f82f242009-11-18 22:49:29 +00004474 // Don't consider existing declarations that are in a different
4475 // scope and are out-of-semantic-context declarations (if the new
4476 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00004477 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004478 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004479
David Blaikiebbafb8a2012-03-11 07:00:24 +00004480 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004481 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4482 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004483 // Merge the decl with the existing one if appropriate.
4484 if (!Previous.empty()) {
4485 if (Previous.isSingleResult() &&
4486 isa<FieldDecl>(Previous.getFoundDecl()) &&
4487 D.getCXXScopeSpec().isSet()) {
4488 // The user tried to define a non-static data member
4489 // out-of-line (C++ [dcl.meaning]p1).
4490 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4491 << D.getCXXScopeSpec().getRange();
4492 Previous.clear();
4493 NewVD->setInvalidDecl();
4494 }
4495 } else if (D.getCXXScopeSpec().isSet()) {
4496 // No previous declaration in the qualifying scope.
4497 Diag(D.getIdentifierLoc(), diag::err_no_member)
4498 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004499 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004500 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004501 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004502
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004503 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004504
4505 // This is an explicit specialization of a static data member. Check it.
4506 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4507 CheckMemberSpecialization(NewVD, Previous))
4508 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004509 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00004510
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004511 // If this is a locally-scoped extern C variable, update the map of
4512 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00004513 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004514 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004515 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004516
Eli Friedman570024a2010-08-05 06:57:20 +00004517 // If there's a #pragma GCC visibility in scope, and this isn't a class
4518 // member, set the visibility of this variable.
4519 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4520 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004521
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004522 MarkUnusedFileScopedDecl(NewVD);
4523
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004524 return NewVD;
4525}
4526
John McCalldf8b37c2010-03-22 09:20:08 +00004527/// \brief Diagnose variable or built-in function shadowing. Implements
4528/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00004529///
John McCalldf8b37c2010-03-22 09:20:08 +00004530/// This method is called whenever a VarDecl is added to a "useful"
4531/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00004532///
John McCall2d8c7602010-03-20 04:12:52 +00004533/// \param S the scope in which the shadowing name is being declared
4534/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00004535///
John McCalldf8b37c2010-03-22 09:20:08 +00004536void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00004537 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004538 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00004539 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00004540 return;
4541
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00004542 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00004543 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00004544 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00004545
4546 DeclContext *NewDC = D->getDeclContext();
4547
John McCall2d8c7602010-03-20 04:12:52 +00004548 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00004549 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00004550 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00004551
John McCalla2a3f7d2010-03-16 21:48:18 +00004552 NamedDecl* ShadowedDecl = R.getFoundDecl();
4553 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4554 return;
4555
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00004556 // Fields are not shadowed by variables in C++ static methods.
4557 if (isa<FieldDecl>(ShadowedDecl))
4558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4559 if (MD->isStatic())
4560 return;
4561
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00004562 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4563 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00004564 // For shadowing external vars, make sure that we point to the global
4565 // declaration, not a locally scoped extern declaration.
4566 for (VarDecl::redecl_iterator
4567 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4568 I != E; ++I)
4569 if (I->isFileVarDecl()) {
4570 ShadowedDecl = *I;
4571 break;
4572 }
4573 }
4574
4575 DeclContext *OldDC = ShadowedDecl->getDeclContext();
4576
John McCall2d8c7602010-03-20 04:12:52 +00004577 // Only warn about certain kinds of shadowing for class members.
4578 if (NewDC && NewDC->isRecord()) {
4579 // In particular, don't warn about shadowing non-class members.
4580 if (!OldDC->isRecord())
4581 return;
4582
4583 // TODO: should we warn about static data members shadowing
4584 // static data members from base classes?
4585
4586 // TODO: don't diagnose for inaccessible shadowed members.
4587 // This is hard to do perfectly because we might friend the
4588 // shadowing context, but that's just a false negative.
4589 }
4590
4591 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00004592 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00004593 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00004594 if (isa<FieldDecl>(ShadowedDecl))
4595 Kind = 3; // field
4596 else
4597 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00004598 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00004599 Kind = 1; // global
4600 else
4601 Kind = 0; // local
4602
John McCall2d8c7602010-03-20 04:12:52 +00004603 DeclarationName Name = R.getLookupName();
4604
John McCalla2a3f7d2010-03-16 21:48:18 +00004605 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00004606 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00004607 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4608}
4609
John McCalldf8b37c2010-03-22 09:20:08 +00004610/// \brief Check -Wshadow without the advantage of a previous lookup.
4611void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004612 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00004613 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004614 return;
4615
John McCalldf8b37c2010-03-22 09:20:08 +00004616 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4617 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4618 LookupName(R, S);
4619 CheckShadow(S, D, R);
4620}
4621
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004622/// \brief Perform semantic checking on a newly-created variable
4623/// declaration.
4624///
4625/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004626/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004627/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004628/// have been translated into a declaration, and to check variables
4629/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004630///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004631/// Sets NewVD->isInvalidDecl() if an error was encountered.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004632///
4633/// Returns true if the variable declaration is a redeclaration.
4634bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4635 LookupResult &Previous) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004636 // If the decl is already known invalid, don't check it.
4637 if (NewVD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004638 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004639
Abramo Bagnara341ab732012-11-08 14:44:42 +00004640 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
4641 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004642
John McCall8b07ec22010-05-15 11:32:37 +00004643 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00004644 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4645 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004646 T = Context.getObjCObjectPointerType(T);
4647 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004648 }
Mike Stump11289f42009-09-09 15:08:12 +00004649
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004650 // Emit an error if an address space was applied to decl with local storage.
4651 // This includes arrays of objects with address space qualifiers, but not
4652 // automatic variables that point to other address spaces.
4653 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00004654 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004655 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004656 NewVD->setInvalidDecl();
4657 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004658 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00004659
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00004660 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
4661 // scope.
4662 if ((getLangOpts().OpenCLVersion >= 120)
4663 && NewVD->isStaticLocal()) {
4664 Diag(NewVD->getLocation(), diag::err_static_function_scope);
4665 NewVD->setInvalidDecl();
4666 return false;
4667 }
4668
Mike Stumpca5ae662009-04-14 00:57:29 +00004669 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004670 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004671 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004672 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00004673 else {
4674 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004675 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00004676 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004677 }
Chris Lattner88fdea82010-10-10 18:16:20 +00004678
Chris Lattner9fecd742009-04-19 05:21:20 +00004679 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00004680 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00004681 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00004682 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004683
Chris Lattner9fecd742009-04-19 05:21:20 +00004684 if ((isVM && NewVD->hasLinkage()) ||
4685 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004686 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004687 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004688 TypeSourceInfo *FixedTInfo =
4689 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4690 SizeIsNegative, Oversized);
4691 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004692 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00004693 // FIXME: This won't give the correct result for
4694 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00004695 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004696
Anders Carlsson6c885802009-02-28 21:56:50 +00004697 if (NewVD->isFileVarDecl())
4698 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004699 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00004700 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00004701 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004702 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00004703 else
4704 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004705 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004706 NewVD->setInvalidDecl();
4707 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004708 }
4709
Abramo Bagnara341ab732012-11-08 14:44:42 +00004710 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004711 if (NewVD->isFileVarDecl())
4712 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4713 else
4714 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004715 NewVD->setInvalidDecl();
4716 return false;
Anders Carlsson6c885802009-02-28 21:56:50 +00004717 }
Mike Stump11289f42009-09-09 15:08:12 +00004718
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004719 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00004720 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004721 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00004722 }
4723
John McCall1f82f242009-11-18 22:49:29 +00004724 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004725 // Since we did not find anything by this name and we're declaring
4726 // an extern "C" variable, look for a non-visible extern "C"
4727 // declaration with the same name.
4728 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00004729 = findLocallyScopedExternalDecl(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004730 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004731 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004732 }
4733
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004734 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004735 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4736 << T;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004737 NewVD->setInvalidDecl();
4738 return false;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004739 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004740
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004741 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004742 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004743 NewVD->setInvalidDecl();
4744 return false;
Mike Stumpe9efa802009-04-30 00:19:40 +00004745 }
Mike Stump11289f42009-09-09 15:08:12 +00004746
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004747 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004748 Diag(NewVD->getLocation(), diag::err_block_on_vm);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004749 NewVD->setInvalidDecl();
4750 return false;
Mike Stumpa7128632009-05-01 23:41:47 +00004751 }
4752
Richard Smith6331c402012-02-13 22:16:19 +00004753 if (NewVD->isConstexpr() && !T->isDependentType() &&
4754 RequireLiteralType(NewVD->getLocation(), T,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00004755 diag::err_constexpr_var_non_literal)) {
Richard Smith6331c402012-02-13 22:16:19 +00004756 NewVD->setInvalidDecl();
4757 return false;
4758 }
4759
John McCall1f82f242009-11-18 22:49:29 +00004760 if (!Previous.empty()) {
John McCall1f82f242009-11-18 22:49:29 +00004761 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004762 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004763 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004764 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004765}
4766
Douglas Gregor36d1b142009-10-06 17:59:45 +00004767/// \brief Data used with FindOverriddenMethod
4768struct FindOverriddenMethodData {
4769 Sema *S;
4770 CXXMethodDecl *Method;
4771};
4772
4773/// \brief Member lookup function that determines whether a given C++
4774/// method overrides a method in a base class, to be used with
4775/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004776static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004777 CXXBasePath &Path,
4778 void *UserData) {
4779 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004780
Douglas Gregor36d1b142009-10-06 17:59:45 +00004781 FindOverriddenMethodData *Data
4782 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004783
4784 DeclarationName Name = Data->Method->getDeclName();
4785
4786 // FIXME: Do we care about other names here too?
4787 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004788 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004789 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4790 CanQualType CT = Data->S->Context.getCanonicalType(T);
4791
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004792 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004793 }
4794
4795 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004796 Path.Decls.first != Path.Decls.second;
4797 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004798 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004799 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4800 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004801 return true;
4802 }
4803 }
4804
4805 return false;
4806}
4807
David Blaikie7e414262012-10-17 00:47:58 +00004808namespace {
4809 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
4810}
4811/// \brief Report an error regarding overriding, along with any relevant
4812/// overriden methods.
4813///
4814/// \param DiagID the primary error to report.
4815/// \param MD the overriding method.
4816/// \param OEK which overrides to include as notes.
4817static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
4818 OverrideErrorKind OEK = OEK_All) {
4819 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
4820 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4821 E = MD->end_overridden_methods();
4822 I != E; ++I) {
4823 // This check (& the OEK parameter) could be replaced by a predicate, but
4824 // without lambdas that would be overkill. This is still nicer than writing
4825 // out the diag loop 3 times.
4826 if ((OEK == OEK_All) ||
4827 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
4828 (OEK == OEK_Deleted && (*I)->isDeleted()))
4829 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
4830 }
4831}
4832
Sebastian Redld5b24532009-11-18 21:51:29 +00004833/// AddOverriddenMethods - See if a method overrides any in the base classes,
4834/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004835bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004836 // Look for virtual methods in base classes that this method might override.
4837 CXXBasePaths Paths;
4838 FindOverriddenMethodData Data;
4839 Data.Method = MD;
4840 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00004841 bool hasDeletedOverridenMethods = false;
4842 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004843 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004844 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4845 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4846 E = Paths.found_decls_end(); I != E; ++I) {
4847 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00004848 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00004849 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00004850 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004851 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00004852 hasDeletedOverridenMethods |= OldMD->isDeleted();
4853 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004854 AddedAny = true;
4855 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004856 }
4857 }
4858 }
David Blaikie7e414262012-10-17 00:47:58 +00004859
4860 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
4861 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
4862 }
4863 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
4864 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
4865 }
4866
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004867 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004868}
4869
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004870namespace {
4871 // Struct for holding all of the extra arguments needed by
4872 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4873 struct ActOnFDArgs {
4874 Scope *S;
4875 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004876 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004877 bool AddToScope;
4878 };
4879}
4880
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004881namespace {
4882
4883// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004884// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004885class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4886 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004887 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
4888 CXXRecordDecl *Parent)
4889 : Context(Context), OriginalFD(TypoFD),
4890 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004891
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004892 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004893 if (candidate.getEditDistance() == 0)
4894 return false;
4895
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004896 llvm::SmallVector<unsigned, 1> MismatchedParams;
4897 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4898 CDeclEnd = candidate.end();
4899 CDecl != CDeclEnd; ++CDecl) {
4900 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4901
4902 if (FD && !FD->hasBody() &&
4903 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
4904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4905 CXXRecordDecl *Parent = MD->getParent();
4906 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
4907 return true;
4908 } else if (!ExpectedParent) {
4909 return true;
4910 }
4911 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004912 }
4913
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004914 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004915 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004916
4917 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004918 ASTContext &Context;
4919 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004920 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004921};
4922
4923}
4924
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004925/// \brief Generate diagnostics for an invalid function redeclaration.
4926///
4927/// This routine handles generating the diagnostic messages for an invalid
4928/// function redeclaration, including finding possible similar declarations
4929/// or performing typo correction if there are no previous declarations with
4930/// the same name.
4931///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00004932/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004933/// the new declaration name does not cause new errors.
4934static NamedDecl* DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004935 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004936 ActOnFDArgs &ExtraArgs) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004937 NamedDecl *Result = NULL;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004938 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004939 DeclContext *NewDC = NewFD->getDeclContext();
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004940 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
John McCallf7cfb222010-10-13 05:45:15 +00004941 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004942 llvm::SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004943 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4944 TypoCorrection Correction;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004945 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004946 ExtraArgs.D.getDeclSpec().isFriendSpecified());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004947 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4948 : diag::err_member_def_does_not_match;
4949
4950 NewFD->setInvalidDecl();
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004951 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00004952 assert(!Prev.isAmbiguous() &&
4953 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004954 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004955 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
4956 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004957 if (!Prev.empty()) {
4958 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4959 Func != FuncEnd; ++Func) {
4960 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004961 if (FD &&
4962 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004963 // Add 1 to the index so that 0 can mean the mismatch didn't
4964 // involve a parameter
4965 unsigned ParamNum =
4966 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4967 NearMatches.push_back(std::make_pair(FD, ParamNum));
4968 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004969 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004970 // If the qualified name lookup yielded nothing, try typo correction
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004971 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004972 Prev.getLookupKind(), 0, 0,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004973 Validator, NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004974 // Trap errors.
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004975 Sema::SFINAETrap Trap(SemaRef);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004976
4977 // Set up everything for the call to ActOnFunctionDeclarator
4978 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4979 ExtraArgs.D.getIdentifierLoc());
4980 Previous.clear();
4981 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004982 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4983 CDeclEnd = Correction.end();
4984 CDecl != CDeclEnd; ++CDecl) {
4985 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004986 if (FD && !FD->hasBody() &&
4987 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004988 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004989 }
4990 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004991 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004992 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4993 // pieces need to verify the typo-corrected C++ declaraction and hopefully
4994 // eliminate the need for the parameter pack ExtraArgs.
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004995 Result = SemaRef.ActOnFunctionDeclarator(
4996 ExtraArgs.S, ExtraArgs.D,
4997 Correction.getCorrectionDecl()->getDeclContext(),
4998 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4999 ExtraArgs.AddToScope);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005000 if (Trap.hasErrorOccurred()) {
5001 // Pretend the typo correction never occurred
5002 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
5003 ExtraArgs.D.getIdentifierLoc());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005004 ExtraArgs.D.setRedeclaration(wasRedeclaration);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005005 Previous.clear();
5006 Previous.setLookupName(Name);
5007 Result = NULL;
5008 } else {
5009 for (LookupResult::iterator Func = Previous.begin(),
5010 FuncEnd = Previous.end();
5011 Func != FuncEnd; ++Func) {
5012 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
5013 NearMatches.push_back(std::make_pair(FD, 0));
5014 }
5015 }
5016 if (NearMatches.empty()) {
5017 // Ignore the correction if it didn't yield any close FunctionDecl matches
5018 Correction = TypoCorrection();
5019 } else {
Kaelyn Uhrain7fbe2f72011-09-14 19:37:32 +00005020 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
5021 : diag::err_member_def_does_not_match_suggest;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005022 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005023 }
5024
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00005025 if (Correction) {
David Blaikie04ea41c2012-10-12 20:00:44 +00005026 // FIXME: use Correction.getCorrectionRange() instead of computing the range
5027 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
5028 // turn causes the correction to fully qualify the name. If we fix
5029 // CorrectTypo to minimally qualify then this change should be good.
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00005030 SourceRange FixItLoc(NewFD->getLocation());
5031 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
5032 if (Correction.getCorrectionSpecifier() && SS.isValid())
5033 FixItLoc.setBegin(SS.getBeginLoc());
5034 SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005035 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005036 << FixItHint::CreateReplacement(
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00005037 FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
5038 } else {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005039 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
5040 << Name << NewDC << NewFD->getLocation();
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00005041 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005042
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00005043 bool NewFDisConst = false;
5044 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00005045 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00005046
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005047 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
5048 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
5049 NearMatch != NearMatchEnd; ++NearMatch) {
5050 FunctionDecl *FD = NearMatch->first;
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00005051 bool FDisConst = false;
5052 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
David Blaikief5697e52012-08-10 00:55:35 +00005053 FDisConst = MD->isConst();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005054
5055 if (unsigned Idx = NearMatch->second) {
5056 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005057 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
5058 if (Loc.isInvalid()) Loc = FD->getLocation();
5059 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005060 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
5061 } else if (Correction) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005062 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005063 << Correction.getQuoted(SemaRef.getLangOpts());
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00005064 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005065 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00005066 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00005067 } else
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005068 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00005069 }
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005070 return Result;
John McCallf7cfb222010-10-13 05:45:15 +00005071}
5072
David Blaikie30d15442011-10-19 22:56:21 +00005073static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
5074 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005075 switch (D.getDeclSpec().getStorageClassSpec()) {
5076 default: llvm_unreachable("Unknown storage class!");
5077 case DeclSpec::SCS_auto:
5078 case DeclSpec::SCS_register:
5079 case DeclSpec::SCS_mutable:
5080 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5081 diag::err_typecheck_sclass_func);
5082 D.setInvalidType();
5083 break;
5084 case DeclSpec::SCS_unspecified: break;
5085 case DeclSpec::SCS_extern: return SC_Extern;
5086 case DeclSpec::SCS_static: {
5087 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5088 // C99 6.7.1p5:
5089 // The declaration of an identifier for a function that has
5090 // block scope shall have no explicit storage-class specifier
5091 // other than extern
5092 // See also (C++ [dcl.stc]p4).
5093 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5094 diag::err_static_block_func);
5095 break;
5096 } else
5097 return SC_Static;
5098 }
5099 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5100 }
5101
5102 // No explicit storage class has already been returned
5103 return SC_None;
5104}
5105
5106static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
5107 DeclContext *DC, QualType &R,
5108 TypeSourceInfo *TInfo,
5109 FunctionDecl::StorageClass SC,
5110 bool &IsVirtualOkay) {
5111 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
5112 DeclarationName Name = NameInfo.getName();
5113
5114 FunctionDecl *NewFD = 0;
5115 bool isInline = D.getDeclSpec().isInlineSpecified();
5116 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
5117 FunctionDecl::StorageClass SCAsWritten
5118 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
5119
David Blaikiebbafb8a2012-03-11 07:00:24 +00005120 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005121 // Determine whether the function was written with a
5122 // prototype. This true when:
5123 // - there is a prototype in the declarator, or
5124 // - the type R of the function is some kind of typedef or other reference
5125 // to a type name (which eventually refers to a function type).
5126 bool HasPrototype =
5127 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
5128 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
5129
David Blaikie30d15442011-10-19 22:56:21 +00005130 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005131 D.getLocStart(), NameInfo, R,
David Blaikie30d15442011-10-19 22:56:21 +00005132 TInfo, SC, SCAsWritten, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005133 HasPrototype);
5134 if (D.isInvalidType())
5135 NewFD->setInvalidDecl();
5136
5137 // Set the lexical context.
5138 NewFD->setLexicalDeclContext(SemaRef.CurContext);
5139
5140 return NewFD;
5141 }
5142
5143 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5144 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5145
5146 // Check that the return type is not an abstract class type.
5147 // For record types, this is done by the AbstractClassUsageDiagnoser once
5148 // the class has been completely parsed.
5149 if (!DC->isRecord() &&
5150 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
5151 R->getAs<FunctionType>()->getResultType(),
5152 diag::err_abstract_type_in_decl,
5153 SemaRef.AbstractReturnType))
5154 D.setInvalidType();
5155
5156 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
5157 // This is a C++ constructor declaration.
5158 assert(DC->isRecord() &&
5159 "Constructors can only be declared in a member context");
5160
5161 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
5162 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005163 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005164 R, TInfo, isExplicit, isInline,
5165 /*isImplicitlyDeclared=*/false,
5166 isConstexpr);
5167
5168 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5169 // This is a C++ destructor declaration.
5170 if (DC->isRecord()) {
5171 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
5172 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
5173 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
5174 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005175 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005176 NameInfo, R, TInfo, isInline,
5177 /*isImplicitlyDeclared=*/false);
5178
5179 // If the class is complete, then we now create the implicit exception
5180 // specification. If the class is incomplete or dependent, we can't do
5181 // it yet.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005182 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005183 Record->getDefinition() && !Record->isBeingDefined() &&
5184 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
5185 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
5186 }
5187
5188 IsVirtualOkay = true;
5189 return NewDD;
5190
5191 } else {
5192 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
5193 D.setInvalidType();
5194
5195 // Create a FunctionDecl to satisfy the function definition parsing
5196 // code path.
5197 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005198 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005199 D.getIdentifierLoc(), Name, R, TInfo,
5200 SC, SCAsWritten, isInline,
5201 /*hasPrototype=*/true, isConstexpr);
5202 }
5203
5204 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
5205 if (!DC->isRecord()) {
5206 SemaRef.Diag(D.getIdentifierLoc(),
5207 diag::err_conv_function_not_member);
5208 return 0;
5209 }
5210
5211 SemaRef.CheckConversionDeclarator(D, R, SC);
5212 IsVirtualOkay = true;
5213 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005214 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005215 R, TInfo, isInline, isExplicit,
5216 isConstexpr, SourceLocation());
5217
5218 } else if (DC->isRecord()) {
5219 // If the name of the function is the same as the name of the record,
5220 // then this must be an invalid constructor that has a return type.
5221 // (The parser checks for a return type and makes the declarator a
5222 // constructor if it has no return type).
5223 if (Name.getAsIdentifierInfo() &&
5224 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5225 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5226 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5227 << SourceRange(D.getIdentifierLoc());
5228 return 0;
5229 }
5230
5231 bool isStatic = SC == SC_Static;
5232
5233 // [class.free]p1:
5234 // Any allocation function for a class T is a static member
5235 // (even if not explicitly declared static).
5236 if (Name.getCXXOverloadedOperator() == OO_New ||
5237 Name.getCXXOverloadedOperator() == OO_Array_New)
5238 isStatic = true;
5239
5240 // [class.free]p6 Any deallocation function for a class X is a static member
5241 // (even if not explicitly declared static).
5242 if (Name.getCXXOverloadedOperator() == OO_Delete ||
5243 Name.getCXXOverloadedOperator() == OO_Array_Delete)
5244 isStatic = true;
5245
5246 IsVirtualOkay = !isStatic;
5247
5248 // This is a C++ method declaration.
5249 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005250 D.getLocStart(), NameInfo, R,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005251 TInfo, isStatic, SCAsWritten, isInline,
5252 isConstexpr, SourceLocation());
5253
5254 } else {
5255 // Determine whether the function was written with a
5256 // prototype. This true when:
5257 // - we're in C++ (where every function has a prototype),
5258 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005259 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005260 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5261 true/*HasPrototype*/, isConstexpr);
5262 }
5263}
5264
Eli Friedman8f5e9832012-09-20 01:40:23 +00005265void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
5266 // In C++, the empty parameter-type-list must be spelled "void"; a
5267 // typedef of void is not permitted.
5268 if (getLangOpts().CPlusPlus &&
5269 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5270 bool IsTypeAlias = false;
5271 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5272 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5273 else if (const TemplateSpecializationType *TST =
5274 Param->getType()->getAs<TemplateSpecializationType>())
5275 IsTypeAlias = TST->isTypeAlias();
5276 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5277 << IsTypeAlias;
5278 }
5279}
5280
Mike Stump11289f42009-09-09 15:08:12 +00005281NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00005282Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005283 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00005284 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005285 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005286 QualType R = TInfo->getType();
5287
Zhongxing Xubece5d62009-01-16 01:13:29 +00005288 assert(R.getTypePtr()->isFunctionType());
5289
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005290 // TODO: consider using NameInfo for diagnostic.
5291 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5292 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005293 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005294
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005295 if (D.getDeclSpec().isThreadSpecified())
5296 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5297
Chris Lattner347eec92009-04-11 19:17:25 +00005298 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00005299 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00005300 Diag(D.getIdentifierLoc(),
5301 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005302 << R->getAs<FunctionType>()->getResultType()
5303 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005304
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005305 QualType T = R->getAs<FunctionType>()->getResultType();
5306 T = Context.getObjCObjectPointerType(T);
5307 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5308 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5309 R = Context.getFunctionType(T, FPT->arg_type_begin(),
5310 FPT->getNumArgs(), EPI);
5311 }
5312 else if (isa<FunctionNoProtoType>(R))
5313 R = Context.getFunctionNoProtoType(T);
Chris Lattner347eec92009-04-11 19:17:25 +00005314 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005315
Douglas Gregor513e63c2010-12-10 19:28:19 +00005316 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00005317 FunctionTemplateDecl *FunctionTemplate = 0;
5318 bool isExplicitSpecialization = false;
5319 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00005320
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005321 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00005322 bool HasExplicitTemplateArgs = false;
5323 TemplateArgumentListInfo TemplateArgs;
5324
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005325 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00005326
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005327 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5328 isVirtualOkay);
5329 if (!NewFD) return 0;
5330
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00005331 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5332 NewFD->setTopLevelDeclInObjCContainer();
5333
David Blaikiebbafb8a2012-03-11 07:00:24 +00005334 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005335 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00005336 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5337 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00005338 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005339 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005340 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00005341 // C++ [class.friend]p5
5342 // A function can be defined in a friend declaration of a
5343 // class . . . . Such a function is implicitly inline.
5344 NewFD->setImplicitlyInline();
5345 }
5346
John McCalldb632ac2012-09-25 07:32:39 +00005347 // If this is a method defined in an __interface, and is not a constructor
5348 // or an overloaded operator, then set the pure flag (isVirtual will already
5349 // return true).
5350 if (const CXXRecordDecl *Parent =
5351 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
5352 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00005353 NewFD->setPure(true);
5354 }
5355
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005356 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005357 isExplicitSpecialization = false;
5358 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005359 if (D.isInvalidType())
5360 NewFD->setInvalidDecl();
5361
5362 // Set the lexical context. If the declarator has a C++
5363 // scope specifier, or is the object of a friend declaration, the
5364 // lexical context will be different from the semantic context.
5365 NewFD->setLexicalDeclContext(CurContext);
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005366
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005367 // Match up the template parameter lists with the scope specifier, then
5368 // determine whether we have a template or a template specialization.
5369 bool Invalid = false;
5370 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00005371 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005372 D.getDeclSpec().getLocStart(),
Douglas Gregor972fe532011-05-10 18:27:06 +00005373 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00005374 D.getCXXScopeSpec(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005375 TemplateParamLists.data(),
John McCall2c2eb122010-10-16 06:59:13 +00005376 TemplateParamLists.size(),
5377 isFriend,
5378 isExplicitSpecialization,
5379 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00005380 if (TemplateParams->size() > 0) {
5381 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005382
Abramo Bagnara60804e12011-03-18 15:16:37 +00005383 // Check that we can declare a template here.
5384 if (CheckTemplateDeclScope(S, TemplateParams))
5385 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005386
Abramo Bagnara60804e12011-03-18 15:16:37 +00005387 // A destructor cannot be a template.
5388 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5389 Diag(NewFD->getLocation(), diag::err_destructor_template);
5390 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00005391 }
Douglas Gregor041b0842011-10-14 15:31:12 +00005392
5393 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00005394 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00005395 // now that we know what the current instantiation is.
5396 if (DC->isDependentContext()) {
5397 ContextRAII SavedContext(*this, DC);
5398 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5399 Invalid = true;
5400 }
5401
John McCall1f0479e2010-03-24 08:27:58 +00005402
Abramo Bagnara60804e12011-03-18 15:16:37 +00005403 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5404 NewFD->getLocation(),
5405 Name, TemplateParams,
5406 NewFD);
5407 FunctionTemplate->setLexicalDeclContext(CurContext);
5408 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5409
5410 // For source fidelity, store the other template param lists.
5411 if (TemplateParamLists.size() > 1) {
5412 NewFD->setTemplateParameterListsInfo(Context,
5413 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005414 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00005415 }
5416 } else {
5417 // This is a function template specialization.
5418 isFunctionTemplateSpecialization = true;
5419 // For source fidelity, store all the template param lists.
5420 NewFD->setTemplateParameterListsInfo(Context,
5421 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005422 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00005423
5424 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5425 if (isFriend) {
5426 // We want to remove the "template<>", found here.
5427 SourceRange RemoveRange = TemplateParams->getSourceRange();
5428
5429 // If we remove the template<> and the name is not a
5430 // template-id, we're actually silently creating a problem:
5431 // the friend declaration will refer to an untemplated decl,
5432 // and clearly the user wants a template specialization. So
5433 // we need to insert '<>' after the name.
5434 SourceLocation InsertLoc;
5435 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5436 InsertLoc = D.getName().getSourceRange().getEnd();
5437 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5438 }
5439
5440 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5441 << Name << RemoveRange
5442 << FixItHint::CreateRemoval(RemoveRange)
5443 << FixItHint::CreateInsertion(InsertLoc, "<>");
5444 }
5445 }
5446 }
5447 else {
5448 // All template param lists were matched against the scope specifier:
5449 // this is NOT (an explicit specialization of) a template.
5450 if (TemplateParamLists.size() > 0)
5451 // For source fidelity, store all the template param lists.
5452 NewFD->setTemplateParameterListsInfo(Context,
5453 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005454 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005455 }
5456
5457 if (Invalid) {
5458 NewFD->setInvalidDecl();
5459 if (FunctionTemplate)
5460 FunctionTemplate->setInvalidDecl();
5461 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005462
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005463 // C++ [dcl.fct.spec]p5:
5464 // The virtual specifier shall only be used in declarations of
5465 // nonstatic class member functions that appear within a
5466 // member-specification of a class declaration; see 10.3.
5467 //
5468 if (isVirtual && !NewFD->isInvalidDecl()) {
5469 if (!isVirtualOkay) {
5470 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5471 diag::err_virtual_non_function);
5472 } else if (!CurContext->isRecord()) {
5473 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00005474 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5475 diag::err_virtual_out_of_class)
5476 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5477 } else if (NewFD->getDescribedFunctionTemplate()) {
5478 // C++ [temp.mem]p3:
5479 // A member function template shall not be virtual.
5480 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5481 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005482 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5483 } else {
5484 // Okay: Add virtual to the method.
5485 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00005486 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00005487 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005488
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005489 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00005490 // The inline specifier shall not appear on a block scope function
5491 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005492 if (isInline && !NewFD->isInvalidDecl()) {
5493 if (CurContext->isFunctionOrMethod()) {
5494 // 'inline' is not allowed on block scope function declaration.
5495 Diag(D.getDeclSpec().getInlineSpecLoc(),
5496 diag::err_inline_declaration_block_scope) << Name
5497 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5498 }
5499 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005500
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005501 // C++ [dcl.fct.spec]p6:
5502 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00005503 // constructor or conversion function within its class definition;
5504 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005505 if (isExplicit && !NewFD->isInvalidDecl()) {
5506 if (!CurContext->isRecord()) {
5507 // 'explicit' was specified outside of the class.
5508 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5509 diag::err_explicit_out_of_class)
5510 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5511 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5512 !isa<CXXConversionDecl>(NewFD)) {
5513 // 'explicit' was specified on a function that wasn't a constructor
5514 // or conversion function.
5515 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5516 diag::err_explicit_non_ctor_or_conv_function)
5517 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5518 }
5519 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005520
Richard Smitha77a0a62011-08-15 21:04:07 +00005521 if (isConstexpr) {
5522 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5523 // are implicitly inline.
5524 NewFD->setImplicitlyInline();
5525
Richard Smitha77a0a62011-08-15 21:04:07 +00005526 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5527 // be either constructors or to return a literal type. Therefore,
5528 // destructors cannot be declared constexpr.
5529 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00005530 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00005531 }
5532
Douglas Gregor26701a42011-09-09 02:06:17 +00005533 // If __module_private__ was specified, mark the function accordingly.
5534 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005535 if (isFunctionTemplateSpecialization) {
5536 SourceLocation ModulePrivateLoc
5537 = D.getDeclSpec().getModulePrivateSpecLoc();
5538 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5539 << 0
5540 << FixItHint::CreateRemoval(ModulePrivateLoc);
5541 } else {
5542 NewFD->setModulePrivate();
5543 if (FunctionTemplate)
5544 FunctionTemplate->setModulePrivate();
5545 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005546 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005547
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005548 if (isFriend) {
5549 // For now, claim that the objects have no previous declaration.
5550 if (FunctionTemplate) {
5551 FunctionTemplate->setObjectOfFriendDecl(false);
5552 FunctionTemplate->setAccess(AS_public);
5553 }
5554 NewFD->setObjectOfFriendDecl(false);
5555 NewFD->setAccess(AS_public);
5556 }
5557
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005558 // If a function is defined as defaulted or deleted, mark it as such now.
5559 switch (D.getFunctionDefinitionKind()) {
5560 case FDK_Declaration:
5561 case FDK_Definition:
5562 break;
5563
5564 case FDK_Defaulted:
5565 NewFD->setDefaulted();
5566 break;
5567
5568 case FDK_Deleted:
5569 NewFD->setDeletedAsWritten();
5570 break;
5571 }
5572
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005573 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5574 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005575 // C++ [class.mfct]p2:
5576 // A member function may be defined (8.4) in its class definition, in
5577 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00005578 NewFD->setImplicitlyInline();
5579 }
5580
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005581 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5582 !CurContext->isRecord()) {
5583 // C++ [class.static]p1:
5584 // A data or function member of a class may be declared static
5585 // in a class definition, in which case it is a static member of
5586 // the class.
5587
5588 // Complain about the 'static' specifier if it's on an out-of-line
5589 // member function definition.
5590 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5591 diag::err_static_out_of_line)
5592 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5593 }
Richard Smith66f3ac92012-10-20 08:26:51 +00005594
5595 // C++11 [except.spec]p15:
5596 // A deallocation function with no exception-specification is treated
5597 // as if it were specified with noexcept(true).
5598 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
5599 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
5600 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
5601 getLangOpts().CPlusPlus0x && FPT && !FPT->hasExceptionSpec()) {
5602 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5603 EPI.ExceptionSpecType = EST_BasicNoexcept;
5604 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
5605 FPT->arg_type_begin(),
5606 FPT->getNumArgs(), EPI));
5607 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005608 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005609
5610 // Filter out previous declarations that don't match the scope.
5611 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5612 isExplicitSpecialization ||
5613 isFunctionTemplateSpecialization);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005614
Zhongxing Xubece5d62009-01-16 01:13:29 +00005615 // Handle GNU asm-label extension (encoded as an attribute).
5616 if (Expr *E = (Expr*) D.getAsmLabel()) {
5617 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005618 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005619 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5620 SE->getString()));
David Chisnall0867d9c2012-02-18 16:12:34 +00005621 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5622 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5623 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5624 if (I != ExtnameUndeclaredIdentifiers.end()) {
5625 NewFD->addAttr(I->second);
5626 ExtnameUndeclaredIdentifiers.erase(I);
5627 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005628 }
5629
Chris Lattner9af40c12009-04-25 06:12:16 +00005630 // Copy the parameter declarations from the declarator D to the function
5631 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005632 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00005633 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005634 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00005635
Zhongxing Xubece5d62009-01-16 01:13:29 +00005636 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5637 // function that takes no arguments, not a function that takes a
5638 // single void argument.
5639 // We let through "const void" here because Sema::GetTypeForDeclarator
5640 // already checks for that case.
5641 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5642 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005643 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00005644 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00005645 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00005646 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005647 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00005648 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005649 assert(Param->getDeclContext() != NewFD && "Was set before ?");
5650 Param->setDeclContext(NewFD);
5651 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00005652
5653 if (Param->isInvalidDecl())
5654 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005655 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005656 }
Mike Stump11289f42009-09-09 15:08:12 +00005657
John McCall9dd450b2009-09-21 23:43:11 +00005658 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00005659 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00005660 // following example, we'll need to synthesize (unnamed)
5661 // parameters for use in the declaration.
5662 //
5663 // @code
5664 // typedef void fn(int);
5665 // fn f;
5666 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005667
Chris Lattner47c0d002009-04-25 06:03:53 +00005668 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00005669 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5670 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00005671 ParmVarDecl *Param =
5672 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00005673 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00005674 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005675 }
Chris Lattner49303b22009-04-25 18:38:18 +00005676 } else {
5677 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5678 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00005679 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005680
Chris Lattner9af40c12009-04-25 06:12:16 +00005681 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00005682 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00005683
James Molloy6f8780b2012-02-29 10:24:19 +00005684 // Find all anonymous symbols defined during the declaration of this function
5685 // and add to NewFD. This lets us track decls such 'enum Y' in:
5686 //
5687 // void f(enum Y {AA} x) {}
5688 //
5689 // which would otherwise incorrectly end up in the translation unit scope.
5690 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5691 DeclsInPrototypeScope.clear();
5692
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005693 // Process the non-inheritable attributes on this declaration.
5694 ProcessDeclAttributes(S, NewFD, D,
5695 /*NonInheritable=*/true, /*Inheritable=*/false);
5696
Richard Smith84208dc2012-03-13 05:56:40 +00005697 // Functions returning a variably modified type violate C99 6.7.5.2p2
5698 // because all functions have linkage.
5699 if (!NewFD->isInvalidDecl() &&
5700 NewFD->getResultType()->isVariablyModifiedType()) {
5701 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5702 NewFD->setInvalidDecl();
5703 }
5704
Rafael Espindolac67f2232012-05-10 02:50:16 +00005705 // Handle attributes.
5706 ProcessDeclAttributes(S, NewFD, D,
5707 /*NonInheritable=*/false, /*Inheritable=*/true);
5708
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00005709 QualType RetType = NewFD->getResultType();
5710 const CXXRecordDecl *Ret = RetType->isRecordType() ?
5711 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
5712 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
5713 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00005714 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5715 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
5716 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
5717 Context));
5718 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00005719 }
5720
David Blaikiebbafb8a2012-03-11 07:00:24 +00005721 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005722 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00005723 bool isExplicitSpecialization=false;
David Blaikied937bf12011-09-08 06:33:04 +00005724 if (!NewFD->isInvalidDecl()) {
Richard Smith84208dc2012-03-13 05:56:40 +00005725 if (NewFD->isMain())
5726 CheckMain(NewFD, D.getDeclSpec());
5727 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5728 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00005729 }
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00005730 // Make graceful recovery from an invalid redeclaration.
5731 else if (!Previous.empty())
5732 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005733 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005734 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5735 "previous declaration set still overloaded");
5736 } else {
5737 // If the declarator is a template-id, translate the parser's template
5738 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005739 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5740 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5741 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5742 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005743 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005744 TemplateId->NumArgs);
5745 translateTemplateArguments(TemplateArgsPtr,
5746 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00005747
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005748 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00005749
Douglas Gregor522d5eb2011-06-06 15:22:55 +00005750 if (NewFD->isInvalidDecl()) {
5751 HasExplicitTemplateArgs = false;
5752 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00005753 // Function template with explicit template arguments.
5754 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5755 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5756
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005757 HasExplicitTemplateArgs = false;
5758 } else if (!isFunctionTemplateSpecialization &&
5759 !D.getDeclSpec().isFriendSpecified()) {
5760 // We have encountered something that the user meant to be a
5761 // specialization (because it has explicitly-specified template
5762 // arguments) but that was not introduced with a "template<>" (or had
5763 // too few of them).
5764 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5765 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5766 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005767 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00005768 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005769 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00005770 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005771 // "friend void foo<>(int);" is an implicit specialization decl.
5772 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00005773 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005774 } else if (isFriend && isFunctionTemplateSpecialization) {
5775 // This combination is only possible in a recovery case; the user
5776 // wrote something like:
5777 // template <> friend void foo(int);
5778 // which we're recovering from as if the user had written:
5779 // friend void foo<>(int);
5780 // Go ahead and fake up a template id.
5781 HasExplicitTemplateArgs = true;
5782 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5783 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005784 }
John McCallf7cfb222010-10-13 05:45:15 +00005785
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005786 // If it's a friend (and only if it's a friend), it's possible
5787 // that either the specialized function type or the specialized
5788 // template is dependent, and therefore matching will fail. In
5789 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00005790 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005791 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00005792 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5793 TemplateSpecializationType::anyDependentTemplateArguments(
5794 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5795 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005796 assert(HasExplicitTemplateArgs &&
5797 "friend function specialization without template args");
5798 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5799 Previous))
5800 NewFD->setInvalidDecl();
5801 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00005802 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00005803 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005804 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005805 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005806 diag::ext_function_specialization_in_class :
5807 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00005808 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00005809 } else if (CheckFunctionTemplateSpecialization(NewFD,
5810 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5811 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005812 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00005813
5814 // C++ [dcl.stc]p1:
5815 // A storage-class-specifier shall not be specified in an explicit
5816 // specialization (14.7.3)
5817 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00005818 if (SC != NewFD->getStorageClass())
5819 Diag(NewFD->getLocation(),
5820 diag::err_explicit_specialization_inconsistent_storage_class)
5821 << SC
5822 << FixItHint::CreateRemoval(
5823 D.getDeclSpec().getStorageClassSpecLoc());
5824
5825 else
5826 Diag(NewFD->getLocation(),
5827 diag::ext_explicit_specialization_storage_class)
5828 << FixItHint::CreateRemoval(
5829 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00005830 }
5831
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005832 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5833 if (CheckMemberSpecialization(NewFD, Previous))
5834 NewFD->setInvalidDecl();
5835 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005836
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005837 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00005838 if (!isDependentClassScopeExplicitSpecialization) {
5839 if (NewFD->isInvalidDecl()) {
5840 // If this is a class member, mark the class invalid immediately.
5841 // This avoids some consistency errors later.
5842 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5843 methodDecl->getParent()->setInvalidDecl();
5844 } else {
5845 if (NewFD->isMain())
5846 CheckMain(NewFD, D.getDeclSpec());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005847 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5848 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00005849 }
5850 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005851
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005852 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005853 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5854 "previous declaration set still overloaded");
5855
5856 NamedDecl *PrincipalDecl = (FunctionTemplate
5857 ? cast<NamedDecl>(FunctionTemplate)
5858 : NewFD);
5859
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005860 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005861 AccessSpecifier Access = AS_public;
5862 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00005863 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005864
5865 NewFD->setAccess(Access);
5866 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5867
5868 PrincipalDecl->setObjectOfFriendDecl(true);
5869 }
5870
5871 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5872 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5873 PrincipalDecl->setNonMemberOperator();
5874
5875 // If we have a function template, check the template parameter
5876 // list. This will check and merge default template arguments.
5877 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00005878 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00005879 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005880 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00005881 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005882 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005883 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005884 ? TPC_FriendFunctionTemplateDefinition
5885 : TPC_FriendFunctionTemplate)
5886 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00005887 DC && DC->isRecord() &&
5888 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005889 ? TPC_ClassTemplateMember
5890 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005891 }
5892
5893 if (NewFD->isInvalidDecl()) {
5894 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005895 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005896 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005897 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005898 // Fake up an access specifier if it's supposed to be a class member.
5899 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5900 NewFD->setAccess(AS_public);
5901
5902 // Qualified decls generally require a previous declaration.
5903 if (D.getCXXScopeSpec().isSet()) {
5904 // ...with the major exception of templated-scope or
5905 // dependent-scope friend declarations.
5906
5907 // TODO: we currently also suppress this check in dependent
5908 // contexts because (1) the parameter depth will be off when
5909 // matching friend templates and (2) we might actually be
5910 // selecting a friend based on a dependent factor. But there
5911 // are situations where these conditions don't apply and we
5912 // can actually do this check immediately.
5913 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00005914 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005915 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5916 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005917 // ignore these
5918 } else {
5919 // The user tried to provide an out-of-line definition for a
5920 // function that is a member of a class or namespace, but there
5921 // was no such member function declared (C++ [class.mfct]p2,
5922 // C++ [namespace.memdef]p2). For example:
5923 //
5924 // class X {
5925 // void f() const;
5926 // };
5927 //
5928 // void X::f() { } // ill-formed
5929 //
5930 // Complain about this problem, and attempt to suggest close
5931 // matches (e.g., those that differ only in cv-qualifiers and
5932 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005933
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005934 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005935 NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005936 ExtraArgs)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005937 AddToScope = ExtraArgs.AddToScope;
5938 return Result;
5939 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005940 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005941
5942 // Unqualified local friend declarations are required to resolve
5943 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005944 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005945 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005946 NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005947 ExtraArgs)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005948 AddToScope = ExtraArgs.AddToScope;
5949 return Result;
5950 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005951 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005952
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005953 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005954 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00005955 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005956 // An out-of-line member function declaration must also be a
5957 // definition (C++ [dcl.meaning]p1).
5958 // Note that this is not the case for explicit specializations of
5959 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00005960 // C++ [temp.expl.spec]p2. We also allow these declarations as an
5961 // extension for compatibility with old SWIG code which likes to
5962 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005963 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5964 << D.getCXXScopeSpec().getRange();
5965 }
5966 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005967
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005968 AddKnownFunctionAttributes(NewFD);
5969
Douglas Gregor72609052010-08-06 13:50:58 +00005970 if (NewFD->hasAttr<OverloadableAttr>() &&
5971 !NewFD->getType()->getAs<FunctionProtoType>()) {
5972 Diag(NewFD->getLocation(),
5973 diag::err_attribute_overloadable_no_prototype)
5974 << NewFD;
5975
5976 // Turn this into a variadic function with no parameters.
5977 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005978 FunctionProtoType::ExtProtoInfo EPI;
5979 EPI.Variadic = true;
5980 EPI.ExtInfo = FT->getExtInfo();
5981
5982 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00005983 NewFD->setType(R);
5984 }
5985
Eli Friedman570024a2010-08-05 06:57:20 +00005986 // If there's a #pragma GCC visibility in scope, and this isn't a class
5987 // member, set the visibility of this function.
5988 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5989 AddPushedVisibilityAttribute(NewFD);
5990
John McCall32f5fe12011-09-30 05:12:12 +00005991 // If there's a #pragma clang arc_cf_code_audited in scope, consider
5992 // marking the function.
5993 AddCFAuditedAttribute(NewFD);
5994
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005995 // If this is a locally-scoped extern C function, update the
5996 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00005997 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005998 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00005999 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00006000
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00006001 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00006002 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00006003
David Blaikiebbafb8a2012-03-11 07:00:24 +00006004 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006005 if (FunctionTemplate) {
6006 if (NewFD->isInvalidDecl())
6007 FunctionTemplate->setInvalidDecl();
6008 return FunctionTemplate;
6009 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006010 }
Mike Stump11289f42009-09-09 15:08:12 +00006011
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00006012 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
6013 if ((getLangOpts().OpenCLVersion >= 120)
6014 && NewFD->hasAttr<OpenCLKernelAttr>()
6015 && (SC == SC_Static)) {
6016 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
6017 D.setInvalidType();
6018 }
6019
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006020 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00006021
David Blaikiebbafb8a2012-03-11 07:00:24 +00006022 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00006023 if (IdentifierInfo *II = NewFD->getIdentifier())
6024 if (!NewFD->isInvalidDecl() &&
6025 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6026 if (II->isStr("cudaConfigureCall")) {
6027 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
6028 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
6029
6030 Context.setcudaConfigureCallDecl(NewFD);
6031 }
6032 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006033
6034 // Here we have an function template explicit specialization at class scope.
6035 // The actually specialization will be postponed to template instatiation
6036 // time via the ClassScopeFunctionSpecializationDecl node.
6037 if (isDependentClassScopeExplicitSpecialization) {
6038 ClassScopeFunctionSpecializationDecl *NewSpec =
6039 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00006040 Context, CurContext, SourceLocation(),
6041 cast<CXXMethodDecl>(NewFD),
6042 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006043 CurContext->addDecl(NewSpec);
6044 AddToScope = false;
6045 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00006046
Douglas Gregorf4f296d2009-03-23 23:06:20 +00006047 return NewFD;
6048}
6049
6050/// \brief Perform semantic checking of a new function declaration.
6051///
6052/// Performs semantic analysis of the new function declaration
6053/// NewFD. This routine performs all semantic checking that does not
6054/// require the actual declarator involved in the declaration, and is
6055/// used both for the declaration of functions as they are parsed
6056/// (called via ActOnDeclarator) and for the declaration of functions
6057/// that have been instantiated via C++ template instantiation (called
6058/// via InstantiateDecl).
6059///
James Dennettffad8b72012-06-22 08:10:18 +00006060/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00006061/// an explicit specialization of the previous declaration.
6062///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006063/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006064///
James Dennettffad8b72012-06-22 08:10:18 +00006065/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006066bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00006067 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006068 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00006069 assert(!NewFD->getResultType()->isVariablyModifiedType()
6070 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00006071
Douglas Gregorf4f296d2009-03-23 23:06:20 +00006072 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00006073 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006074 // Since we did not find anything by this name and we're declaring
6075 // an extern "C" function, look for a non-visible extern "C"
6076 // declaration with the same name.
6077 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00006078 = findLocallyScopedExternalDecl(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006079 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00006080 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006081 }
6082
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006083 bool Redeclaration = false;
6084
Douglas Gregore62c0a42009-02-24 01:23:02 +00006085 // Merge or overload the declaration with an existing declaration of
6086 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00006087 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00006088 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00006089 // a declaration that requires merging. If it's an overload,
6090 // there's no more work to do here; we'll just add the new
6091 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00006092
John McCall1f82f242009-11-18 22:49:29 +00006093 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00006094 if (!AllowOverloadingOfFunction(Previous, Context)) {
6095 Redeclaration = true;
6096 OldDecl = Previous.getFoundDecl();
6097 } else {
John McCalle9cccd82010-06-16 08:42:20 +00006098 switch (CheckOverload(S, NewFD, Previous, OldDecl,
6099 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00006100 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006101 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00006102 break;
6103
6104 case Ovl_NonFunction:
6105 Redeclaration = true;
6106 break;
6107
6108 case Ovl_Overload:
6109 Redeclaration = false;
6110 break;
John McCall1f82f242009-11-18 22:49:29 +00006111 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00006112
David Blaikiebbafb8a2012-03-11 07:00:24 +00006113 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00006114 // If a function name is overloadable in C, then every function
6115 // with that name must be marked "overloadable".
6116 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
6117 << Redeclaration << NewFD;
6118 NamedDecl *OverloadedDecl = 0;
6119 if (Redeclaration)
6120 OverloadedDecl = OldDecl;
6121 else if (!Previous.empty())
6122 OverloadedDecl = Previous.getRepresentativeDecl();
6123 if (OverloadedDecl)
6124 Diag(OverloadedDecl->getLocation(),
6125 diag::note_attribute_overloadable_prev_overload);
6126 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
6127 Context));
6128 }
John McCall1f82f242009-11-18 22:49:29 +00006129 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006130
John McCall1f82f242009-11-18 22:49:29 +00006131 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00006132 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00006133 // merged.
James Molloye9430032012-03-13 08:55:35 +00006134 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006135 NewFD->setInvalidDecl();
6136 return Redeclaration;
6137 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006138
John McCall1f82f242009-11-18 22:49:29 +00006139 Previous.clear();
6140 Previous.addDecl(OldDecl);
6141
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006142 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00006143 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
David Blaikie30d15442011-10-19 22:56:21 +00006144 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00006145 FunctionTemplateDecl *NewTemplateDecl
6146 = NewFD->getDescribedFunctionTemplate();
6147 assert(NewTemplateDecl && "Template/non-template mismatch");
6148 if (CXXMethodDecl *Method
6149 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
6150 Method->setAccess(OldTemplateDecl->getAccess());
6151 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
6152 }
Douglas Gregorcf915552009-10-13 16:30:37 +00006153
6154 // If this is an explicit specialization of a member that is a function
6155 // template, mark it as a member specialization.
6156 if (IsExplicitSpecialization &&
6157 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
6158 NewTemplateDecl->setMemberSpecialization();
6159 assert(OldTemplateDecl->isMemberSpecialization());
6160 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00006161
Douglas Gregorca027af2009-10-12 22:27:17 +00006162 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006163 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
6164 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006165 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006166 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006167 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00006168 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006169
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006170 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006171 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006172 // C++-specific checks.
6173 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
6174 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006175 } else if (CXXDestructorDecl *Destructor =
6176 dyn_cast<CXXDestructorDecl>(NewFD)) {
6177 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006178 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006179
Douglas Gregor7454c562010-07-02 20:37:36 +00006180 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00006181 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006182 if (!ClassType->isDependentType()) {
6183 DeclarationName Name
6184 = Context.DeclarationNames.getCXXDestructorName(
6185 Context.getCanonicalType(ClassType));
6186 if (NewFD->getDeclName() != Name) {
6187 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006188 NewFD->setInvalidDecl();
6189 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006190 }
6191 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006192 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00006193 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006194 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00006195 }
6196
6197 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00006198 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
6199 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00006200 !Method->getDescribedFunctionTemplate() &&
6201 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006202 if (AddOverriddenMethods(Method->getParent(), Method)) {
6203 // If the function was marked as "static", we have a problem.
6204 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00006205 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006206 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006207 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006208 }
Douglas Gregor3024f072012-04-16 07:05:22 +00006209
6210 if (Method->isStatic())
6211 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00006212 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006213
6214 // Extra checking for C++ overloaded operators (C++ [over.oper]).
6215 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006216 CheckOverloadedOperatorDeclaration(NewFD)) {
6217 NewFD->setInvalidDecl();
6218 return Redeclaration;
6219 }
Alexis Huntc88db062010-01-13 09:01:02 +00006220
6221 // Extra checking for C++0x literal operators (C++0x [over.literal]).
6222 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006223 CheckLiteralOperatorDeclaration(NewFD)) {
6224 NewFD->setInvalidDecl();
6225 return Redeclaration;
6226 }
Alexis Huntc88db062010-01-13 09:01:02 +00006227
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006228 // In C++, check default arguments now that we have merged decls. Unless
6229 // the lexical context is the class, because in this case this is done
6230 // during delayed parsing anyway.
6231 if (!CurContext->isRecord())
6232 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00006233
6234 // If this function declares a builtin function, check the type of this
6235 // declaration against the expected type for the builtin.
6236 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6237 ASTContext::GetBuiltinTypeError Error;
6238 QualType T = Context.GetBuiltinType(BuiltinID, Error);
6239 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6240 // The type of this function differs from the type of the builtin,
6241 // so forget about the builtin entirely.
6242 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6243 }
6244 }
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00006245
6246 // If this function is declared as being extern "C", then check to see if
6247 // the function returns a UDT (class, struct, or union type) that is not C
6248 // compatible, and if it does, warn the user.
6249 if (NewFD->isExternC()) {
6250 QualType R = NewFD->getResultType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00006251 if (R->isIncompleteType() && !R->isVoidType())
6252 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
6253 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00006254 else if (!R.isPODType(Context) && !R->isVoidType() &&
6255 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00006256 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00006257 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006258 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006259 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00006260}
6261
David Blaikied937bf12011-09-08 06:33:04 +00006262void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00006263 // C++11 [basic.start.main]p3: A program that declares main to be inline,
6264 // static or constexpr is ill-formed.
John McCall02dee0a2009-07-25 04:36:53 +00006265 // C99 6.7.4p4: In a hosted environment, the inline function specifier
6266 // shall not appear in a declaration of main.
6267 // static main is not an error under C99, but we should warn about it.
David Blaikied937bf12011-09-08 06:33:04 +00006268 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00006269 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00006270 ? diag::err_static_main : diag::warn_static_main)
6271 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6272 if (FD->isInlineSpecified())
6273 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6274 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Richard Smith3f333f22012-02-04 06:10:17 +00006275 if (FD->isConstexpr()) {
6276 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6277 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6278 FD->setConstexpr(false);
6279 }
John McCall02dee0a2009-07-25 04:36:53 +00006280
6281 QualType T = FD->getType();
6282 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00006283 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00006284
John McCall5ed3caf2012-02-14 19:50:52 +00006285 // All the standards say that main() should should return 'int'.
6286 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6287 // In C and C++, main magically returns 0 if you fall off the end;
6288 // set the flag which tells us that.
6289 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6290 FD->setHasImplicitReturnZero(true);
6291
6292 // In C with GNU extensions we allow main() to have non-integer return
6293 // type, but we should warn about the extension, and we disable the
6294 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006295 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00006296 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6297
6298 // Otherwise, this is just a flat-out error.
6299 } else {
Douglas Gregorf05c0952011-02-19 19:04:23 +00006300 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00006301 FD->setInvalidDecl(true);
6302 }
6303
6304 // Treat protoless main() as nullary.
6305 if (isa<FunctionNoProtoType>(FT)) return;
6306
6307 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6308 unsigned nparams = FTP->getNumArgs();
6309 assert(FD->getNumParams() == nparams);
6310
John McCall0e21fcc2009-12-24 09:58:38 +00006311 bool HasExtraParameters = (nparams > 3);
6312
6313 // Darwin passes an undocumented fourth argument of type char**. If
6314 // other platforms start sprouting these, the logic below will start
6315 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00006316 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00006317 HasExtraParameters = false;
6318
6319 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00006320 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6321 FD->setInvalidDecl(true);
6322 nparams = 3;
6323 }
6324
6325 // FIXME: a lot of the following diagnostics would be improved
6326 // if we had some location information about types.
6327
6328 QualType CharPP =
6329 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00006330 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00006331
6332 for (unsigned i = 0; i < nparams; ++i) {
6333 QualType AT = FTP->getArgType(i);
6334
6335 bool mismatch = true;
6336
6337 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6338 mismatch = false;
6339 else if (Expected[i] == CharPP) {
6340 // As an extension, the following forms are okay:
6341 // char const **
6342 // char const * const *
6343 // char * const *
6344
John McCall8ccfcb52009-09-24 19:53:00 +00006345 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00006346 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006347 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6348 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00006349 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6350 qs.removeConst();
6351 mismatch = !qs.empty();
6352 }
6353 }
6354
6355 if (mismatch) {
6356 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6357 // TODO: suggest replacing given type with expected type
6358 FD->setInvalidDecl(true);
6359 }
6360 }
6361
6362 if (nparams == 1 && !FD->isInvalidDecl()) {
6363 Diag(FD->getLocation(), diag::warn_main_one_arg);
6364 }
Douglas Gregorbff62032010-10-21 16:57:46 +00006365
6366 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6367 Diag(FD->getLocation(), diag::err_main_template_decl);
6368 FD->setInvalidDecl();
6369 }
John McCalld9baf6a2009-07-24 03:03:21 +00006370}
6371
Eli Friedmand5a55bd2008-05-20 13:48:25 +00006372bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00006373 // FIXME: Need strict checking. In C89, we need to check for
6374 // any assignment, increment, decrement, function-calls, or
6375 // commas outside of a sizeof. In C99, it's the same list,
6376 // except that the aforementioned are allowed in unevaluated
6377 // expressions. Everything else falls under the
6378 // "may accept other forms of constant expressions" exception.
6379 // (We never end up here for C++, so the constant expression
6380 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00006381 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00006382 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00006383 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6384 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00006385 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00006386}
6387
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006388namespace {
6389 // Visits an initialization expression to see if OrigDecl is evaluated in
6390 // its own initialization and throws a warning if it does.
6391 class SelfReferenceChecker
6392 : public EvaluatedExprVisitor<SelfReferenceChecker> {
6393 Sema &S;
6394 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006395 bool isRecordType;
6396 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00006397 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006398
6399 public:
6400 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6401
6402 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00006403 S(S), OrigDecl(OrigDecl) {
6404 isPODType = false;
6405 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00006406 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006407 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6408 isPODType = VD->getType().isPODType(S.Context);
6409 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00006410 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00006411 }
6412 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006413
Richard Trieu64c51ab2012-05-09 00:21:34 +00006414 // For most expressions, the cast is directly above the DeclRefExpr.
6415 // For conditional operators, the cast can be outside the conditional
6416 // operator if both expressions are DeclRefExpr's.
6417 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00006418 if (isReferenceType)
6419 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00006420 E = E->IgnoreParenImpCasts();
6421 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
6422 HandleDeclRefExpr(DRE);
6423 return;
6424 }
6425
6426 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6427 HandleValue(CO->getTrueExpr());
6428 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00006429 return;
6430 }
6431
6432 if (isa<MemberExpr>(E)) {
6433 Expr *Base = E->IgnoreParenImpCasts();
6434 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6435 // Check for static member variables and don't warn on them.
6436 if (!isa<FieldDecl>(ME->getMemberDecl()))
6437 return;
6438 Base = ME->getBase()->IgnoreParenImpCasts();
6439 }
6440 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
6441 HandleDeclRefExpr(DRE);
6442 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00006443 }
6444 }
6445
Richard Trieu32673472012-10-01 17:39:51 +00006446 // Reference types are handled here since all uses of references are
6447 // bad, not just r-value uses.
6448 void VisitDeclRefExpr(DeclRefExpr *E) {
6449 if (isReferenceType)
6450 HandleDeclRefExpr(E);
6451 }
6452
Richard Trieu64c51ab2012-05-09 00:21:34 +00006453 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00006454 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00006455 (isRecordType && E->getCastKind() == CK_NoOp))
6456 HandleValue(E->getSubExpr());
6457
6458 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006459 }
6460
Richard Trieua04ad1a2011-09-01 21:44:13 +00006461 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00006462 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00006463 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00006464
Richard Trieu742c6ed2012-10-03 00:41:36 +00006465 // Warn when a non-static method call is followed by non-static member
6466 // field accesses, which is followed by a DeclRefExpr.
6467 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
6468 bool Warn = (MD && !MD->isStatic());
6469 Expr *Base = E->getBase()->IgnoreParenImpCasts();
6470 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6471 if (!isa<FieldDecl>(ME->getMemberDecl()))
6472 Warn = false;
6473 Base = ME->getBase()->IgnoreParenImpCasts();
6474 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00006475
Richard Trieu742c6ed2012-10-03 00:41:36 +00006476 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
6477 if (Warn)
6478 HandleDeclRefExpr(DRE);
6479 return;
6480 }
6481
6482 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
6483 // Visit that expression.
6484 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006485 }
6486
Richard Trieua04ad1a2011-09-01 21:44:13 +00006487 void VisitUnaryOperator(UnaryOperator *E) {
6488 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00006489 if (E->getOpcode() == UO_AddrOf && isRecordType &&
6490 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
6491 if (!isPODType)
6492 HandleValue(E->getSubExpr());
6493 return;
6494 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00006495 Inherited::VisitUnaryOperator(E);
6496 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00006497
6498 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
6499
Richard Trieua04ad1a2011-09-01 21:44:13 +00006500 void HandleDeclRefExpr(DeclRefExpr *DRE) {
6501 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006502 if (OrigDecl != ReferenceDecl) return;
Hans Wennborgd799a2b2012-08-20 08:52:22 +00006503 unsigned diag = isReferenceType
6504 ? diag::warn_uninit_self_reference_in_reference_init
6505 : diag::warn_uninit_self_reference_in_init;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006506 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00006507 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00006508 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006509 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00006510 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006511 }
6512 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006513
Richard Trieu32673472012-10-01 17:39:51 +00006514 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6515 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
6516 bool DirectInit) {
6517 // Parameters arguments are occassionially constructed with itself,
6518 // for instance, in recursive functions. Skip them.
6519 if (isa<ParmVarDecl>(OrigDecl))
6520 return;
6521
6522 E = E->IgnoreParens();
6523
6524 // Skip checking T a = a where T is not a record or reference type.
6525 // Doing so is a way to silence uninitialized warnings.
6526 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
6527 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
6528 if (ICE->getCastKind() == CK_LValueToRValue)
6529 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
6530 if (DRE->getDecl() == OrigDecl)
6531 return;
6532
6533 SelfReferenceChecker(S, OrigDecl).Visit(E);
6534 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00006535}
6536
Douglas Gregor5fb53972009-01-14 15:45:31 +00006537/// AddInitializerToDecl - Adds the initializer Init to the
6538/// declaration dcl. If DirectInit is true, this is C++ direct
6539/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00006540void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6541 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00006542 // If there is no declaration, there was an error parsing it. Just ignore
6543 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00006544 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00006545 return;
Mike Stump11289f42009-09-09 15:08:12 +00006546
Douglas Gregor0c880302009-03-11 23:00:04 +00006547 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6548 // With declarators parsed the way they are, the parser cannot
6549 // distinguish between a normal initializer and a pure-specifier.
6550 // Thus this grotesque test.
6551 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00006552 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00006553 Context.getCanonicalType(IL->getType()) == Context.IntTy)
6554 CheckPureMethod(Method, Init->getSourceRange());
6555 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00006556 Diag(Method->getLocation(), diag::err_member_function_initialization)
6557 << Method->getDeclName() << Init->getSourceRange();
6558 Method->setInvalidDecl();
6559 }
6560 return;
6561 }
6562
Steve Naroff437b4d82007-09-12 20:13:48 +00006563 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6564 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00006565 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6566 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00006567 RealDecl->setInvalidDecl();
6568 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00006569 }
6570
Sebastian Redla9351792012-02-11 23:51:47 +00006571 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6572
Richard Smith0cc85782011-12-15 19:20:59 +00006573 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith74801c82012-07-08 04:13:07 +00006574 AutoType *Auto = 0;
6575 if (TypeMayContainAuto &&
6576 (Auto = VDecl->getType()->getContainedAutoType()) &&
6577 !Auto->isDeduced()) {
Sebastian Redla9351792012-02-11 23:51:47 +00006578 Expr *DeduceInit = Init;
6579 // Initializer could be a C++ direct-initializer. Deduction only works if it
6580 // contains exactly one expression.
6581 if (CXXDirectInit) {
6582 if (CXXDirectInit->getNumExprs() == 0) {
6583 // It isn't possible to write this directly, but it is possible to
6584 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006585 Diag(CXXDirectInit->getLocStart(),
Sebastian Redla9351792012-02-11 23:51:47 +00006586 diag::err_auto_var_init_no_expression)
6587 << VDecl->getDeclName() << VDecl->getType()
6588 << VDecl->getSourceRange();
6589 RealDecl->setInvalidDecl();
6590 return;
6591 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006592 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Sebastian Redla9351792012-02-11 23:51:47 +00006593 diag::err_auto_var_init_multiple_expressions)
6594 << VDecl->getDeclName() << VDecl->getType()
6595 << VDecl->getSourceRange();
6596 RealDecl->setInvalidDecl();
6597 return;
6598 } else {
6599 DeduceInit = CXXDirectInit->getExpr(0);
6600 }
6601 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006602 TypeSourceInfo *DeducedType = 0;
Sebastian Redla9351792012-02-11 23:51:47 +00006603 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00006604 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00006605 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9647d3c2011-03-17 16:11:59 +00006606 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006607 RealDecl->setInvalidDecl();
6608 return;
6609 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006610 VDecl->setTypeSourceInfo(DeducedType);
6611 VDecl->setType(DeducedType->getType());
Douglas Gregord5c48442012-02-20 20:05:29 +00006612 VDecl->ClearLinkageCache();
6613
John McCall31168b02011-06-15 23:02:42 +00006614 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006615 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00006616 VDecl->setInvalidDecl();
6617
Jordan Rosed8d56692012-06-08 22:46:07 +00006618 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
6619 // 'id' instead of a specific object type prevents most of our usual checks.
6620 // We only want to warn outside of template instantiations, though:
6621 // inside a template, the 'id' could have come from a parameter.
6622 if (ActiveTemplateInstantiations.empty() &&
6623 DeducedType->getType()->isObjCIdType()) {
6624 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
6625 Diag(Loc, diag::warn_auto_var_is_id)
6626 << VDecl->getDeclName() << DeduceInit->getSourceRange();
6627 }
6628
Richard Smith30482bc2011-02-20 03:19:35 +00006629 // If this is a redeclaration, check that the type we just deduced matches
6630 // the previously declared type.
Douglas Gregorec9fd132012-01-14 16:38:05 +00006631 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith30482bc2011-02-20 03:19:35 +00006632 MergeVarDeclTypes(VDecl, Old);
6633 }
Richard Smith0cc85782011-12-15 19:20:59 +00006634
6635 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6636 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6637 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6638 VDecl->setInvalidDecl();
6639 return;
6640 }
6641
Sebastian Redla9351792012-02-11 23:51:47 +00006642 if (!VDecl->getType()->isDependentType()) {
6643 // A definition must end up with a complete type, which means it must be
6644 // complete with the restriction that an array type might be completed by
6645 // the initializer; note that later code assumes this restriction.
6646 QualType BaseDeclType = VDecl->getType();
6647 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6648 BaseDeclType = Array->getElementType();
6649 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6650 diag::err_typecheck_decl_incomplete_type)) {
6651 RealDecl->setInvalidDecl();
6652 return;
6653 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00006654
Sebastian Redla9351792012-02-11 23:51:47 +00006655 // The variable can not have an abstract class type.
6656 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6657 diag::err_abstract_type_in_decl,
6658 AbstractVariableType))
6659 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00006660 }
6661
Sebastian Redl5ca79842010-02-01 20:16:42 +00006662 const VarDecl *Def;
6663 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00006664 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00006665 << VDecl->getDeclName();
6666 Diag(Def->getLocation(), diag::note_previous_definition);
6667 VDecl->setInvalidDecl();
6668 return;
6669 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00006670
Douglas Gregorf0f83692010-08-24 05:27:49 +00006671 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006672 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00006673 // C++ [class.static.data]p4
6674 // If a static data member is of const integral or const
6675 // enumeration type, its declaration in the class definition can
6676 // specify a constant-initializer which shall be an integral
6677 // constant expression (5.19). In that case, the member can appear
6678 // in integral constant expressions. The member shall still be
6679 // defined in a namespace scope if it is used in the program and the
6680 // namespace scope definition shall not contain an initializer.
6681 //
6682 // We already performed a redefinition check above, but for static
6683 // data members we also need to check whether there was an in-class
6684 // declaration with an initializer.
6685 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikie30d15442011-10-19 22:56:21 +00006686 Diag(VDecl->getLocation(), diag::err_redefinition)
6687 << VDecl->getDeclName();
Douglas Gregor71f39c92010-12-16 01:31:22 +00006688 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6689 return;
6690 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00006691
Douglas Gregor71f39c92010-12-16 01:31:22 +00006692 if (VDecl->hasLocalStorage())
6693 getCurFunction()->setHasBranchProtectedScope();
6694
6695 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6696 VDecl->setInvalidDecl();
6697 return;
6698 }
6699 }
John McCalld4e1b762010-08-01 01:24:59 +00006700
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00006701 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6702 // a kernel function cannot be initialized."
6703 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6704 Diag(VDecl->getLocation(), diag::err_local_cant_init);
6705 VDecl->setInvalidDecl();
6706 return;
6707 }
6708
Steve Naroff61091402007-09-12 14:07:44 +00006709 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00006710 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00006711 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00006712
6713 // Top-level message sends default to 'id' when we're in a debugger
6714 // and we are assigning it to a variable of 'id' type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006715 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00006716 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6717 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6718 if (Result.isInvalid()) {
6719 VDecl->setInvalidDecl();
6720 return;
6721 }
6722 Init = Result.take();
6723 }
Richard Smith0cc85782011-12-15 19:20:59 +00006724
6725 // Perform the initialization.
6726 if (!VDecl->isInvalidDecl()) {
6727 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6728 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00006729 = DirectInit ?
6730 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6731 Init->getLocStart(),
6732 Init->getLocEnd())
6733 : InitializationKind::CreateDirectList(
6734 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00006735 : InitializationKind::CreateCopy(VDecl->getLocation(),
6736 Init->getLocStart());
6737
Sebastian Redla9351792012-02-11 23:51:47 +00006738 Expr **Args = &Init;
6739 unsigned NumArgs = 1;
6740 if (CXXDirectInit) {
6741 Args = CXXDirectInit->getExprs();
6742 NumArgs = CXXDirectInit->getNumExprs();
6743 }
6744 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
Richard Smith0cc85782011-12-15 19:20:59 +00006745 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006746 MultiExprArg(Args, NumArgs), &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00006747 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00006748 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00006749 return;
Steve Naroff61091402007-09-12 14:07:44 +00006750 }
Richard Smith0cc85782011-12-15 19:20:59 +00006751
6752 Init = Result.takeAs<Expr>();
6753 }
6754
Richard Trieu32673472012-10-01 17:39:51 +00006755 // Check for self-references within variable initializers.
6756 // Variables declared within a function/method body (except for references)
6757 // are handled by a dataflow analysis.
6758 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
6759 VDecl->getType()->isReferenceType()) {
6760 CheckSelfReference(*this, RealDecl, Init, DirectInit);
6761 }
6762
Richard Smith0cc85782011-12-15 19:20:59 +00006763 // If the type changed, it means we had an incomplete type that was
6764 // completed by the initializer. For example:
6765 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00006766 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00006767 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00006768 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00006769
6770 // Check any implicit conversions within the expression.
6771 CheckImplicitConversions(Init, VDecl->getLocation());
6772
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006773 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00006774 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6775
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006776 if (VDecl->hasAttr<BlocksAttr>())
6777 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00006778
6779 // It is safe to assign a weak reference into a strong variable.
6780 // Although this code can still have problems:
6781 // id x = self.weakProp;
6782 // id y = self.weakProp;
6783 // we do not warn to warn spuriously when 'x' and 'y' are on separate
6784 // paths through the function. This should be revisited if
6785 // -Wrepeated-use-of-weak is made flow-sensitive.
6786 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
6787 DiagnosticsEngine::Level Level =
6788 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
6789 Init->getLocStart());
6790 if (Level != DiagnosticsEngine::Ignored)
6791 getCurFunction()->markSafeWeakUse(Init);
6792 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006793 }
6794
Richard Smith0cc85782011-12-15 19:20:59 +00006795 Init = MaybeCreateExprWithCleanups(Init);
6796 // Attach the initializer to the decl.
6797 VDecl->setInit(Init);
6798
6799 if (VDecl->isLocalVarDecl()) {
6800 // C99 6.7.8p4: All the expressions in an initializer for an object that has
6801 // static storage duration shall be constant expressions or string literals.
6802 // C++ does not have this restriction.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006803 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
Richard Smith0cc85782011-12-15 19:20:59 +00006804 VDecl->getStorageClass() == SC_Static)
6805 CheckForConstantInitializer(Init, DclT);
Mike Stump11289f42009-09-09 15:08:12 +00006806 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00006807 VDecl->getLexicalDeclContext()->isRecord()) {
6808 // This is an in-class initialization for a static data member, e.g.,
6809 //
6810 // struct S {
6811 // static const int value = 17;
6812 // };
6813
Douglas Gregor0c880302009-03-11 23:00:04 +00006814 // C++ [class.mem]p4:
6815 // A member-declarator can contain a constant-initializer only
6816 // if it declares a static member (9.4) of const integral or
6817 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00006818 //
Richard Smith0cc85782011-12-15 19:20:59 +00006819 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00006820 // If a non-volatile const static data member is of integral or
6821 // enumeration type, its declaration in the class definition can
6822 // specify a brace-or-equal-initializer in which every initalizer-clause
6823 // that is an assignment-expression is a constant expression. A static
6824 // data member of literal type can be declared in the class definition
6825 // with the constexpr specifier; if so, its declaration shall specify a
6826 // brace-or-equal-initializer in which every initializer-clause that is
6827 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00006828
6829 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00006830 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00006831
Richard Smith2316cd82011-09-29 19:11:37 +00006832 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00006833 // type. We separately check that every constexpr variable is of literal
6834 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00006835 } else if (VDecl->isConstexpr()) {
6836
John McCalldb768922010-09-10 23:21:22 +00006837 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00006838 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00006839 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6840 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00006841 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00006842
6843 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00006844 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00006845 // Check whether the expression is a constant expression.
6846 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006847 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00006848 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00006849 // in-class initializer cannot be volatile.
6850 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6851 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00006852 ; // Nothing to check.
6853 else if (Init->isIntegerConstantExpr(Context, &Loc))
6854 ; // Ok, it's an ICE!
6855 else if (Init->isEvaluatable(Context)) {
6856 // If we can constant fold the initializer through heroics, accept it,
6857 // but report this as a use of an extension for -pedantic.
6858 Diag(Loc, diag::ext_in_class_initializer_non_constant)
6859 << Init->getSourceRange();
6860 } else {
6861 // Otherwise, this is some crazy unknown case. Report the issue at the
6862 // location provided by the isIntegerConstantExpr failed check.
6863 Diag(Loc, diag::err_in_class_initializer_non_constant)
6864 << Init->getSourceRange();
6865 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00006866 }
6867
Richard Smith0cc85782011-12-15 19:20:59 +00006868 // We allow foldable floating-point constants as an extension.
6869 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smith2316cd82011-09-29 19:11:37 +00006870 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006871 << DclT << Init->getSourceRange();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006872 if (getLangOpts().CPlusPlus0x)
Richard Smith7b729cd2011-09-30 00:33:19 +00006873 Diag(VDecl->getLocation(),
6874 diag::note_in_class_initializer_float_type_constexpr)
6875 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
John McCalldb768922010-09-10 23:21:22 +00006876
Richard Smith0cc85782011-12-15 19:20:59 +00006877 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
John McCalldb768922010-09-10 23:21:22 +00006878 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6879 << Init->getSourceRange();
6880 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00006881 }
Richard Smith256336d2011-09-29 23:18:34 +00006882
Richard Smith0cc85782011-12-15 19:20:59 +00006883 // Suggest adding 'constexpr' in C++11 for literal types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006884 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
Richard Smith256336d2011-09-29 23:18:34 +00006885 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006886 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00006887 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6888 VDecl->setConstexpr(true);
6889
Richard Smith2316cd82011-09-29 19:11:37 +00006890 } else {
6891 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006892 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00006893 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00006894 }
Steve Naroff08899ff2008-04-15 22:42:06 +00006895 } else if (VDecl->isFileVarDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00006896 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006897 (!getLangOpts().CPlusPlus ||
Douglas Gregorfceea362010-04-22 14:36:26 +00006898 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00006899 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00006900
Richard Smith0cc85782011-12-15 19:20:59 +00006901 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006902 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00006903 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00006904 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00006905
Sebastian Redla9351792012-02-11 23:51:47 +00006906 // We will represent direct-initialization similarly to copy-initialization:
6907 // int x(1); -as-> int x = 1;
6908 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6909 //
6910 // Clients that want to distinguish between the two forms, can check for
6911 // direct initializer using VarDecl::getInitStyle().
6912 // A major benefit is that clients that don't particularly care about which
6913 // exactly form was it (like the CodeGen) can handle both cases without
6914 // special case code.
6915
6916 // C++ 8.5p11:
6917 // The form of initialization (using parentheses or '=') is generally
6918 // insignificant, but does matter when the entity being initialized has a
6919 // class type.
6920 if (CXXDirectInit) {
6921 assert(DirectInit && "Call-style initializer must be direct init.");
6922 VDecl->setInitStyle(VarDecl::CallInit);
6923 } else if (DirectInit) {
6924 // This must be list-initialization. No other way is direct-initialization.
6925 VDecl->setInitStyle(VarDecl::ListInit);
6926 }
6927
John McCall8b7fd8f12011-01-19 11:48:09 +00006928 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00006929}
6930
John McCalleae5acb2010-03-31 02:13:20 +00006931/// ActOnInitializerError - Given that there was an error parsing an
6932/// initializer for the given declaration, try to return to some form
6933/// of sanity.
John McCall48871652010-08-21 09:40:31 +00006934void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00006935 // Our main concern here is re-establishing invariants like "a
6936 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00006937 if (!D || D->isInvalidDecl()) return;
6938
6939 VarDecl *VD = dyn_cast<VarDecl>(D);
6940 if (!VD) return;
6941
Richard Smith30482bc2011-02-20 03:19:35 +00006942 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00006943 if (ParsingInitForAutoVars.count(D)) {
6944 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00006945 return;
6946 }
6947
John McCalleae5acb2010-03-31 02:13:20 +00006948 QualType Ty = VD->getType();
6949 if (Ty->isDependentType()) return;
6950
6951 // Require a complete type.
6952 if (RequireCompleteType(VD->getLocation(),
6953 Context.getBaseElementType(Ty),
6954 diag::err_typecheck_decl_incomplete_type)) {
6955 VD->setInvalidDecl();
6956 return;
6957 }
6958
6959 // Require an abstract type.
6960 if (RequireNonAbstractType(VD->getLocation(), Ty,
6961 diag::err_abstract_type_in_decl,
6962 AbstractVariableType)) {
6963 VD->setInvalidDecl();
6964 return;
6965 }
6966
6967 // Don't bother complaining about constructors or destructors,
6968 // though.
6969}
6970
John McCall48871652010-08-21 09:40:31 +00006971void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00006972 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00006973 // If there is no declaration, there was an error parsing it. Just ignore it.
6974 if (RealDecl == 0)
6975 return;
6976
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006977 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6978 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00006979
Richard Smithf0215fe2011-12-25 21:17:58 +00006980 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00006981 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00006982 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6983 << Var->getDeclName() << Type;
6984 Var->setInvalidDecl();
6985 return;
6986 }
Mike Stump11289f42009-09-09 15:08:12 +00006987
Richard Smithf0215fe2011-12-25 21:17:58 +00006988 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00006989 // the constexpr specifier; if so, its declaration shall specify
6990 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00006991 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6992 // the definition of a variable [...] or the declaration of a static data
6993 // member.
6994 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6995 if (Var->isStaticDataMember())
6996 Diag(Var->getLocation(),
6997 diag::err_constexpr_static_mem_var_requires_init)
6998 << Var->getDeclName();
6999 else
7000 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00007001 Var->setInvalidDecl();
7002 return;
7003 }
7004
Douglas Gregore6565622010-02-09 07:26:29 +00007005 switch (Var->isThisDeclarationADefinition()) {
7006 case VarDecl::Definition:
7007 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
7008 break;
7009
7010 // We have an out-of-line definition of a static data member
7011 // that has an in-class initializer, so we type-check this like
7012 // a declaration.
7013 //
7014 // Fall through
7015
7016 case VarDecl::DeclarationOnly:
7017 // It's only a declaration.
7018
7019 // Block scope. C99 6.7p7: If an identifier for an object is
7020 // declared with no linkage (C99 6.2.2p6), the type for the
7021 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00007022 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00007023 !Var->getLinkage() && !Var->isInvalidDecl() &&
7024 RequireCompleteType(Var->getLocation(), Type,
7025 diag::err_typecheck_decl_incomplete_type))
7026 Var->setInvalidDecl();
7027
7028 // Make sure that the type is not abstract.
7029 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7030 RequireNonAbstractType(Var->getLocation(), Type,
7031 diag::err_abstract_type_in_decl,
7032 AbstractVariableType))
7033 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00007034 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00007035 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00007036 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00007037 Diag(Var->getLocation(), diag::note_private_extern);
7038 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00007039
Douglas Gregore6565622010-02-09 07:26:29 +00007040 return;
7041
7042 case VarDecl::TentativeDefinition:
7043 // File scope. C99 6.9.2p2: A declaration of an identifier for an
7044 // object that has file scope without an initializer, and without a
7045 // storage-class specifier or with the storage-class specifier "static",
7046 // constitutes a tentative definition. Note: A tentative definition with
7047 // external linkage is valid (C99 6.2.2p5).
7048 if (!Var->isInvalidDecl()) {
7049 if (const IncompleteArrayType *ArrayT
7050 = Context.getAsIncompleteArrayType(Type)) {
7051 if (RequireCompleteType(Var->getLocation(),
7052 ArrayT->getElementType(),
7053 diag::err_illegal_decl_array_incomplete_type))
7054 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00007055 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00007056 // C99 6.9.2p3: If the declaration of an identifier for an object is
7057 // a tentative definition and has internal linkage (C99 6.2.2p3), the
7058 // declared type shall not be an incomplete type.
7059 // NOTE: code such as the following
7060 // static struct s;
7061 // struct s { int a; };
7062 // is accepted by gcc. Hence here we issue a warning instead of
7063 // an error and we do not invalidate the static declaration.
7064 // NOTE: to avoid multiple warnings, only check the first declaration.
Douglas Gregorec9fd132012-01-14 16:38:05 +00007065 if (Var->getPreviousDecl() == 0)
Douglas Gregore6565622010-02-09 07:26:29 +00007066 RequireCompleteType(Var->getLocation(), Type,
7067 diag::ext_typecheck_decl_incomplete_type);
7068 }
7069 }
7070
7071 // Record the tentative definition; we're done.
7072 if (!Var->isInvalidDecl())
7073 TentativeDefinitions.push_back(Var);
7074 return;
7075 }
7076
7077 // Provide a specific diagnostic for uninitialized variable
7078 // definitions with incomplete array type.
7079 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00007080 Diag(Var->getLocation(),
7081 diag::err_typecheck_incomplete_array_needs_initializer);
7082 Var->setInvalidDecl();
7083 return;
7084 }
7085
John McCalla755f0f2010-08-01 01:25:24 +00007086 // Provide a specific diagnostic for uninitialized variable
7087 // definitions with reference type.
7088 if (Type->isReferenceType()) {
7089 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
7090 << Var->getDeclName()
7091 << SourceRange(Var->getLocation(), Var->getLocation());
7092 Var->setInvalidDecl();
7093 return;
7094 }
Douglas Gregore6565622010-02-09 07:26:29 +00007095
7096 // Do not attempt to type-check the default initializer for a
7097 // variable with dependent type.
7098 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00007099 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007100
Douglas Gregore6565622010-02-09 07:26:29 +00007101 if (Var->isInvalidDecl())
7102 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00007103
Douglas Gregore6565622010-02-09 07:26:29 +00007104 if (RequireCompleteType(Var->getLocation(),
7105 Context.getBaseElementType(Type),
7106 diag::err_typecheck_decl_incomplete_type)) {
7107 Var->setInvalidDecl();
7108 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007109 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007110
Douglas Gregore6565622010-02-09 07:26:29 +00007111 // The variable can not have an abstract class type.
7112 if (RequireNonAbstractType(Var->getLocation(), Type,
7113 diag::err_abstract_type_in_decl,
7114 AbstractVariableType)) {
7115 Var->setInvalidDecl();
7116 return;
7117 }
7118
Douglas Gregor9574af62011-05-21 17:52:48 +00007119 // Check for jumps past the implicit initializer. C++0x
7120 // clarifies that this applies to a "variable with automatic
7121 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00007122 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00007123 // A program that jumps from a point where a variable with automatic
7124 // storage duration is not in scope to a point where it is in scope is
7125 // ill-formed unless the variable has scalar type, class type with a
7126 // trivial default constructor and a trivial destructor, a cv-qualified
7127 // version of one of these types, or an array of one of the preceding
7128 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007129 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00007130 if (const RecordType *Record
7131 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00007132 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00007133 // Mark the function for further checking even if the looser rules of
7134 // C++11 do not require such checks, so that we can diagnose
7135 // incompatibilities with C++98.
7136 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00007137 getCurFunction()->setHasBranchProtectedScope();
7138 }
Douglas Gregore6565622010-02-09 07:26:29 +00007139 }
Douglas Gregor9574af62011-05-21 17:52:48 +00007140
7141 // C++03 [dcl.init]p9:
7142 // If no initializer is specified for an object, and the
7143 // object is of (possibly cv-qualified) non-POD class type (or
7144 // array thereof), the object shall be default-initialized; if
7145 // the object is of const-qualified type, the underlying class
7146 // type shall have a user-declared default
7147 // constructor. Otherwise, if no initializer is specified for
7148 // a non- static object, the object and its subobjects, if
7149 // any, have an indeterminate initial value); if the object
7150 // or any of its subobjects are of const-qualified type, the
7151 // program is ill-formed.
7152 // C++0x [dcl.init]p11:
7153 // If no initializer is specified for an object, the object is
7154 // default-initialized; [...].
7155 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
7156 InitializationKind Kind
7157 = InitializationKind::CreateDefault(Var->getLocation());
7158
7159 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007160 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
Douglas Gregor9574af62011-05-21 17:52:48 +00007161 if (Init.isInvalid())
7162 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00007163 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00007164 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00007165 // This is important for template substitution.
7166 Var->setInitStyle(VarDecl::CallInit);
7167 }
Douglas Gregor589973b2010-03-08 02:45:10 +00007168
John McCall8b7fd8f12011-01-19 11:48:09 +00007169 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007170 }
7171}
7172
Richard Smith02e85f32011-04-14 22:09:26 +00007173void Sema::ActOnCXXForRangeDecl(Decl *D) {
7174 VarDecl *VD = dyn_cast<VarDecl>(D);
7175 if (!VD) {
7176 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
7177 D->setInvalidDecl();
7178 return;
7179 }
7180
7181 VD->setCXXForRangeDecl(true);
7182
7183 // for-range-declaration cannot be given a storage class specifier.
7184 int Error = -1;
7185 switch (VD->getStorageClassAsWritten()) {
7186 case SC_None:
7187 break;
7188 case SC_Extern:
7189 Error = 0;
7190 break;
7191 case SC_Static:
7192 Error = 1;
7193 break;
7194 case SC_PrivateExtern:
7195 Error = 2;
7196 break;
7197 case SC_Auto:
7198 Error = 3;
7199 break;
7200 case SC_Register:
7201 Error = 4;
7202 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00007203 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00007204 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00007205 }
Richard Smith2316cd82011-09-29 19:11:37 +00007206 if (VD->isConstexpr())
7207 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00007208 if (Error != -1) {
7209 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
7210 << VD->getDeclName() << Error;
7211 D->setInvalidDecl();
7212 }
7213}
7214
John McCall8b7fd8f12011-01-19 11:48:09 +00007215void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
7216 if (var->isInvalidDecl()) return;
7217
John McCall31168b02011-06-15 23:02:42 +00007218 // In ARC, don't allow jumps past the implicit initialization of a
7219 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007220 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00007221 var->hasLocalStorage()) {
7222 switch (var->getType().getObjCLifetime()) {
7223 case Qualifiers::OCL_None:
7224 case Qualifiers::OCL_ExplicitNone:
7225 case Qualifiers::OCL_Autoreleasing:
7226 break;
7227
7228 case Qualifiers::OCL_Weak:
7229 case Qualifiers::OCL_Strong:
7230 getCurFunction()->setHasBranchProtectedScope();
7231 break;
7232 }
7233 }
7234
Eli Friedman7d14b3c2012-10-23 20:19:32 +00007235 if (var->isThisDeclarationADefinition() &&
7236 var->getLinkage() == ExternalLinkage) {
7237 // Find a previous declaration that's not a definition.
7238 VarDecl *prev = var->getPreviousDecl();
7239 while (prev && prev->isThisDeclarationADefinition())
7240 prev = prev->getPreviousDecl();
7241
7242 if (!prev)
7243 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
7244 }
7245
John McCall8b7fd8f12011-01-19 11:48:09 +00007246 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007247 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00007248
Richard Smithde63d362012-11-09 23:03:14 +00007249 QualType type = var->getType();
7250 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00007251
7252 // __block variables might require us to capture a copy-initializer.
7253 if (var->hasAttr<BlocksAttr>()) {
7254 // It's currently invalid to ever have a __block variable with an
7255 // array type; should we diagnose that here?
7256
7257 // Regardless, we don't want to ignore array nesting when
7258 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00007259 if (type->isStructureOrClassType()) {
7260 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00007261 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
John McCall8b7fd8f12011-01-19 11:48:09 +00007262 ExprResult result =
7263 PerformCopyInitialization(
7264 InitializedEntity::InitializeBlock(poi, type, false),
7265 poi, Owned(varRef));
7266 if (!result.isInvalid()) {
7267 result = MaybeCreateExprWithCleanups(result);
7268 Expr *init = result.takeAs<Expr>();
7269 Context.setBlockVarCopyInits(var, init);
7270 }
7271 }
7272 }
7273
Richard Smitheda3c842011-11-07 22:16:17 +00007274 Expr *Init = var->getInit();
7275 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00007276 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00007277
Richard Smithbf830092012-10-29 18:26:47 +00007278 if (!var->getDeclContext()->isDependentContext() &&
7279 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00007280 if (IsGlobal && !var->isConstexpr() &&
7281 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7282 var->getLocation())
7283 != DiagnosticsEngine::Ignored &&
7284 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
Richard Smitheda3c842011-11-07 22:16:17 +00007285 Diag(var->getLocation(), diag::warn_global_constructor)
7286 << Init->getSourceRange();
Richard Smithd0b4dd62011-12-19 06:19:21 +00007287
Richard Smithd0b4dd62011-12-19 06:19:21 +00007288 if (var->isConstexpr()) {
7289 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
7290 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7291 SourceLocation DiagLoc = var->getLocation();
7292 // If the note doesn't add any useful information other than a source
7293 // location, fold it into the primary diagnostic.
7294 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7295 diag::note_invalid_subexpr_in_const_expr) {
7296 DiagLoc = Notes[0].first;
7297 Notes.clear();
7298 }
7299 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7300 << var << Init->getSourceRange();
7301 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7302 Diag(Notes[I].first, Notes[I].second);
7303 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00007304 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00007305 // Check whether the initializer of a const variable of integral or
7306 // enumeration type is an ICE now, since we can't tell whether it was
7307 // initialized by a constant expression if we check later.
7308 var->checkInitIsICE();
7309 }
Richard Smitheda3c842011-11-07 22:16:17 +00007310 }
John McCall8b7fd8f12011-01-19 11:48:09 +00007311
7312 // Require the destructor.
7313 if (const RecordType *recordType = baseType->getAs<RecordType>())
7314 FinalizeVarWithDestructor(var, recordType);
7315}
7316
Richard Smithb2bc2e62011-02-21 20:05:19 +00007317/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7318/// any semantic actions necessary after any initializer has been attached.
7319void
7320Sema::FinalizeDeclaration(Decl *ThisDecl) {
7321 // Note that we are no longer parsing the initializer for this declaration.
7322 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007323
7324 // Now we have parsed the initializer and can update the table of magic
7325 // tag values.
7326 if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) {
7327 const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl);
7328 if (VD && VD->getType()->isIntegralOrEnumerationType()) {
7329 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7330 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
7331 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
7332 I != E; ++I) {
7333 const Expr *MagicValueExpr = VD->getInit();
7334 if (!MagicValueExpr) {
7335 continue;
7336 }
7337 llvm::APSInt MagicValueInt;
7338 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
7339 Diag(I->getRange().getBegin(),
7340 diag::err_type_tag_for_datatype_not_ice)
7341 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7342 continue;
7343 }
7344 if (MagicValueInt.getActiveBits() > 64) {
7345 Diag(I->getRange().getBegin(),
7346 diag::err_type_tag_for_datatype_too_large)
7347 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7348 continue;
7349 }
7350 uint64_t MagicValue = MagicValueInt.getZExtValue();
7351 RegisterTypeTagForDatatype(I->getArgumentKind(),
7352 MagicValue,
7353 I->getMatchingCType(),
7354 I->getLayoutCompatible(),
7355 I->getMustBeNull());
7356 }
7357 }
7358 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00007359}
7360
John McCallba7bf592010-08-24 05:47:05 +00007361Sema::DeclGroupPtrTy
7362Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
7363 Decl **Group, unsigned NumDecls) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007364 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00007365
7366 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00007367 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00007368
Richard Smith2abf6762011-02-23 00:37:57 +00007369 for (unsigned i = 0; i != NumDecls; ++i)
7370 if (Decl *D = Group[i])
7371 Decls.push_back(D);
7372
David Blaikie095deba2012-11-14 01:52:05 +00007373 if (DeclSpec::isDeclRep(DS.getTypeSpecType()))
7374 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()))
7375 getASTContext().addUnnamedTag(Tag);
7376
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007377 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00007378 DS.getTypeSpecType() == DeclSpec::TST_auto);
7379}
7380
7381/// BuildDeclaratorGroup - convert a list of declarations into a declaration
7382/// group, performing any necessary semantic checking.
7383Sema::DeclGroupPtrTy
7384Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
7385 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00007386 // C++0x [dcl.spec.auto]p7:
7387 // If the type deduced for the template parameter U is not the same in each
7388 // deduction, the program is ill-formed.
7389 // FIXME: When initializer-list support is added, a distinction is needed
7390 // between the deduced type U and the deduced type which 'auto' stands for.
7391 // auto a = 0, b = { 1, 2, 3 };
7392 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00007393 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00007394 QualType Deduced;
7395 CanQualType DeducedCanon;
7396 VarDecl *DeducedDecl = 0;
7397 for (unsigned i = 0; i != NumDecls; ++i) {
7398 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
7399 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00007400 // Don't reissue diagnostics when instantiating a template.
7401 if (AT && D->isInvalidDecl())
7402 break;
Richard Smith30482bc2011-02-20 03:19:35 +00007403 if (AT && AT->isDeduced()) {
7404 QualType U = AT->getDeducedType();
7405 CanQualType UCanon = Context.getCanonicalType(U);
7406 if (Deduced.isNull()) {
7407 Deduced = U;
7408 DeducedCanon = UCanon;
7409 DeducedDecl = D;
7410 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00007411 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
7412 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00007413 << Deduced << DeducedDecl->getDeclName()
7414 << U << D->getDeclName()
7415 << DeducedDecl->getInit()->getSourceRange()
7416 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00007417 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00007418 break;
7419 }
7420 }
7421 }
7422 }
7423 }
7424
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007425 ActOnDocumentableDecls(Group, NumDecls);
7426
Richard Smith2abf6762011-02-23 00:37:57 +00007427 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00007428}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00007429
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007430void Sema::ActOnDocumentableDecl(Decl *D) {
7431 ActOnDocumentableDecls(&D, 1);
7432}
7433
7434void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
7435 // Don't parse the comment if Doxygen diagnostics are ignored.
7436 if (NumDecls == 0 || !Group[0])
7437 return;
7438
7439 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
7440 Group[0]->getLocation())
7441 == DiagnosticsEngine::Ignored)
7442 return;
7443
7444 if (NumDecls >= 2) {
7445 // This is a decl group. Normally it will contain only declarations
7446 // procuded from declarator list. But in case we have any definitions or
7447 // additional declaration references:
7448 // 'typedef struct S {} S;'
7449 // 'typedef struct S *S;'
7450 // 'struct S *pS;'
7451 // FinalizeDeclaratorGroup adds these as separate declarations.
7452 Decl *MaybeTagDecl = Group[0];
7453 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
7454 Group++;
7455 NumDecls--;
7456 }
7457 }
7458
7459 // See if there are any new comments that are not attached to a decl.
7460 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
7461 if (!Comments.empty() &&
7462 !Comments.back()->isAttached()) {
7463 // There is at least one comment that not attached to a decl.
7464 // Maybe it should be attached to one of these decls?
7465 //
7466 // Note that this way we pick up not only comments that precede the
7467 // declaration, but also comments that *follow* the declaration -- thanks to
7468 // the lookahead in the lexer: we've consumed the semicolon and looked
7469 // ahead through comments.
7470 for (unsigned i = 0; i != NumDecls; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00007471 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007472 }
7473}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00007474
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007475/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
7476/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00007477Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00007478 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00007479
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007480 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Peter Collingbourne99eddc32011-10-21 11:55:09 +00007481 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00007482 VarDecl::StorageClass StorageClass = SC_None;
7483 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00007484 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00007485 StorageClass = SC_Register;
7486 StorageClassAsWritten = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007487 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00007488 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
7489 StorageClass = SC_Auto;
7490 StorageClassAsWritten = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00007491 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007492 Diag(DS.getStorageClassSpecLoc(),
7493 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00007494 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007495 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007496
7497 if (D.getDeclSpec().isThreadSpecified())
7498 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00007499 if (D.getDeclSpec().isConstexprSpecified())
7500 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
7501 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007502
Eli Friedman574c7452009-04-07 19:37:57 +00007503 DiagnoseFunctionSpecifiers(D);
7504
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00007505 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00007506 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00007507
David Blaikiebbafb8a2012-03-11 07:00:24 +00007508 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00007509 // Check that there are no default arguments inside the type of this
7510 // parameter.
7511 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00007512
7513 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
7514 if (D.getCXXScopeSpec().isSet()) {
7515 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
7516 << D.getCXXScopeSpec().getRange();
7517 D.getCXXScopeSpec().clear();
7518 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00007519 }
7520
Alexis Hunta56cbcc2010-11-03 01:07:06 +00007521 // Ensure we have a valid name
7522 IdentifierInfo *II = 0;
7523 if (D.hasName()) {
7524 II = D.getIdentifier();
7525 if (!II) {
7526 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7527 << GetNameForDeclarator(D).getName().getAsString();
7528 D.setInvalidType(true);
7529 }
7530 }
7531
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00007532 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00007533 if (II) {
John McCall84f02672010-03-18 06:42:38 +00007534 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7535 ForRedeclaration);
7536 LookupName(R, S);
7537 if (R.isSingleResult()) {
7538 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00007539 if (PrevDecl->isTemplateParameter()) {
7540 // Maybe we will complain about the shadowed template parameter.
7541 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7542 // Just pretend that we didn't see the previous declaration.
7543 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00007544 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00007545 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00007546 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007547
Chris Lattnerd9773512009-01-21 02:38:50 +00007548 // Recover by removing the name
7549 II = 0;
7550 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007551 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00007552 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007553 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00007554 }
Steve Naroff773df5c2007-08-07 22:44:21 +00007555
John McCallf7b2fb52010-01-22 00:28:27 +00007556 // Temporarily put parameter variables in the translation unit, not
7557 // the enclosing context. This prevents them from accidentally
7558 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00007559 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007560 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00007561 D.getIdentifierLoc(), II,
7562 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007563 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00007564
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007565 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00007566 New->setInvalidDecl();
7567
7568 assert(S->isFunctionPrototypeScope());
7569 assert(S->getFunctionPrototypeDepth() >= 1);
7570 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7571 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00007572
Douglas Gregor91f84212008-12-11 16:49:14 +00007573 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00007574 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00007575 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00007576 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00007577
Douglas Gregor758a8692009-06-17 21:51:59 +00007578 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00007579
Douglas Gregor41866812011-09-12 18:37:38 +00007580 if (D.getDeclSpec().isModulePrivateSpecified())
7581 Diag(New->getLocation(), diag::err_module_private_local)
7582 << 1 << New->getDeclName()
7583 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7584 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7585
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007586 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00007587 Diag(New->getLocation(), diag::err_block_on_nonlocal);
7588 }
John McCall48871652010-08-21 09:40:31 +00007589 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00007590}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00007591
John McCalla3ccba02010-06-04 11:21:44 +00007592/// \brief Synthesizes a variable for a parameter arising from a
7593/// typedef.
7594ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7595 SourceLocation Loc,
7596 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007597 /* FIXME: setting StartLoc == Loc.
7598 Would it be worth to modify callers so as to provide proper source
7599 location for the unnamed parameters, embedding the parameter's type? */
7600 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00007601 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007602 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00007603 Param->setImplicit();
7604 return Param;
7605}
7606
John McCallc5990642010-08-24 09:05:15 +00007607void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7608 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00007609 // Don't diagnose unused-parameter errors in template instantiations; we
7610 // will already have done so in the template itself.
7611 if (!ActiveTemplateInstantiations.empty())
7612 return;
7613
7614 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00007615 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00007616 !(*Param)->hasAttr<UnusedAttr>()) {
7617 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7618 << (*Param)->getDeclName();
7619 }
7620 }
7621}
7622
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007623void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7624 ParmVarDecl * const *ParamEnd,
7625 QualType ReturnTy,
7626 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007627 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007628 return;
7629
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007630 // Warn if the return value is pass-by-value and larger than the specified
7631 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00007632 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007633 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007634 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007635 Diag(D->getLocation(), diag::warn_return_value_size)
7636 << D->getDeclName() << Size;
7637 }
7638
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007639 // Warn if any parameter is pass-by-value and larger than the specified
7640 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007641 for (; Param != ParamEnd; ++Param) {
7642 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00007643 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007644 continue;
7645 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007646 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007647 Diag((*Param)->getLocation(), diag::warn_parameter_size)
7648 << (*Param)->getDeclName() << Size;
7649 }
7650}
7651
Abramo Bagnaradff19302011-03-08 08:55:46 +00007652ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7653 SourceLocation NameLoc, IdentifierInfo *Name,
7654 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007655 VarDecl::StorageClass StorageClass,
7656 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00007657 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007658 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00007659 T.getObjCLifetime() == Qualifiers::OCL_None &&
7660 T->isObjCLifetimeType()) {
7661
7662 Qualifiers::ObjCLifetime lifetime;
7663
7664 // Special cases for arrays:
7665 // - if it's const, use __unsafe_unretained
7666 // - otherwise, it's an error
7667 if (T->isArrayType()) {
7668 if (!T.isConstQualified()) {
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00007669 DelayedDiagnostics.add(
7670 sema::DelayedDiagnostic::makeForbiddenType(
7671 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
John McCall31168b02011-06-15 23:02:42 +00007672 }
7673 lifetime = Qualifiers::OCL_ExplicitNone;
7674 } else {
7675 lifetime = T->getObjCARCImplicitLifetime();
7676 }
7677 T = Context.getLifetimeQualifiedType(T, lifetime);
7678 }
7679
Abramo Bagnaradff19302011-03-08 08:55:46 +00007680 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00007681 Context.getAdjustedParameterType(T),
7682 TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007683 StorageClass, StorageClassAsWritten,
7684 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00007685
7686 // Parameters can not be abstract class types.
7687 // For record types, this is done by the AbstractClassUsageDiagnoser once
7688 // the class has been completely parsed.
7689 if (!CurContext->isRecord() &&
7690 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7691 AbstractParamType))
7692 New->setInvalidDecl();
7693
7694 // Parameter declarators cannot be interface types. All ObjC objects are
7695 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00007696 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00007697 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00007698 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00007699 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00007700 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00007701 T = Context.getObjCObjectPointerType(T);
7702 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00007703 }
7704
7705 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7706 // duration shall not be qualified by an address-space qualifier."
7707 // Since all parameters have automatic store duration, they can not have
7708 // an address space.
7709 if (T.getAddressSpace() != 0) {
7710 Diag(NameLoc, diag::err_arg_with_address_space);
7711 New->setInvalidDecl();
7712 }
7713
7714 return New;
7715}
7716
Douglas Gregor170512f2009-04-01 23:51:29 +00007717void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7718 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007719 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007720
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007721 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7722 // for a K&R function.
7723 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00007724 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7725 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007726 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007727 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00007728 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00007729 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00007730 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007731 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00007732 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00007733 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00007734
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007735 // Implicitly declare the argument as type 'int' for lack of a better
7736 // type.
John McCall084e83d2011-03-24 11:26:52 +00007737 AttributeFactory attrs;
7738 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007739 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00007740 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00007741 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00007742 PrevSpec, DiagID);
Abramo Bagnara71f32c12012-10-04 21:38:29 +00007743 // Use the identifier location for the type source range.
7744 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
7745 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007746 Declarator ParamD(DS, Declarator::KNRTypeListContext);
7747 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00007748 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007749 }
7750 }
Mike Stump11289f42009-09-09 15:08:12 +00007751 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00007752}
7753
Richard Smith79a52e52012-04-17 22:30:01 +00007754Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00007755 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007756 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00007757 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00007758
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007759 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007760 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00007761 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007762}
7763
Anders Carlsson31c7e882009-12-09 03:30:09 +00007764static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7765 // Don't warn about invalid declarations.
7766 if (FD->isInvalidDecl())
7767 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007768
Anders Carlsson31c7e882009-12-09 03:30:09 +00007769 // Or declarations that aren't global.
7770 if (!FD->isGlobal())
7771 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007772
Anders Carlsson31c7e882009-12-09 03:30:09 +00007773 // Don't warn about C++ member functions.
7774 if (isa<CXXMethodDecl>(FD))
7775 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007776
Anders Carlsson31c7e882009-12-09 03:30:09 +00007777 // Don't warn about 'main'.
7778 if (FD->isMain())
7779 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007780
Anders Carlsson31c7e882009-12-09 03:30:09 +00007781 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00007782 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00007783 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007784
7785 // Don't warn about function templates.
7786 if (FD->getDescribedFunctionTemplate())
7787 return false;
7788
7789 // Don't warn about function template specializations.
7790 if (FD->isFunctionTemplateSpecialization())
7791 return false;
7792
Tanya Lattner4bfc3552012-07-26 00:08:28 +00007793 // Don't warn for OpenCL kernels.
7794 if (FD->hasAttr<OpenCLKernelAttr>())
7795 return false;
7796
Anders Carlsson31c7e882009-12-09 03:30:09 +00007797 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00007798 for (const FunctionDecl *Prev = FD->getPreviousDecl();
7799 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00007800 // Ignore any declarations that occur in function or method
7801 // scope, because they aren't visible from the header.
7802 if (Prev->getDeclContext()->isFunctionOrMethod())
7803 continue;
7804
7805 MissingPrototype = !Prev->getType()->isFunctionProtoType();
7806 break;
7807 }
7808
7809 return MissingPrototype;
7810}
7811
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007812void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7813 // Don't complain if we're in GNU89 mode and the previous definition
7814 // was an extern inline function.
7815 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007816 if (FD->isDefined(Definition) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007817 !canRedefineFunction(Definition, getLangOpts())) {
7818 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007819 Definition->getStorageClass() == SC_Extern)
7820 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007821 << FD->getDeclName() << getLangOpts().CPlusPlus;
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007822 else
7823 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7824 Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smithf716bb82012-08-06 02:25:10 +00007825 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007826 }
7827}
7828
John McCall48871652010-08-21 09:40:31 +00007829Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00007830 // Clear the last template instantiation error context.
7831 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7832
Douglas Gregor17a7c122009-06-24 00:54:41 +00007833 if (!D)
7834 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007835 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00007836
John McCall48871652010-08-21 09:40:31 +00007837 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007838 FD = FunTmpl->getTemplatedDecl();
7839 else
John McCall48871652010-08-21 09:40:31 +00007840 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007841
Douglas Gregor9a28e842010-03-01 23:15:13 +00007842 // Enter a new function scope
7843 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00007844
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007845 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007846 if (!FD->isLateTemplateParsed())
7847 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007848
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007849 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00007850 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00007851 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007852 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00007853 FD->setInvalidDecl();
7854 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007855 }
7856
Eli Friedman9ad72442009-03-04 07:30:59 +00007857 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00007858 // (C99 6.9.1p3, C++ [dcl.fct]p6).
7859 QualType ResultType = FD->getResultType();
7860 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00007861 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00007862 RequireCompleteType(FD->getLocation(), ResultType,
7863 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00007864 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00007865
Douglas Gregorf1b876d2009-03-31 16:35:03 +00007866 // GNU warning -Wmissing-prototypes:
7867 // Warn if a global function is defined without a previous
7868 // prototype declaration. This warning is issued even if the
7869 // definition itself provides a prototype. The aim is to detect
7870 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00007871 if (ShouldWarnAboutMissingPrototype(FD))
7872 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00007873
Douglas Gregor67da0d92009-05-15 17:59:04 +00007874 if (FnBodyScope)
7875 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007876
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007877 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00007878 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7879 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007880
7881 // Introduce our parameters into the function scope
7882 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7883 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00007884 Param->setOwningFunction(FD);
7885
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007886 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00007887 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00007888 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00007889
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00007890 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00007891 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00007892 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007893
James Molloy6f8780b2012-02-29 10:24:19 +00007894 // If we had any tags defined in the function prototype,
7895 // introduce them into the function scope.
7896 if (FnBodyScope) {
7897 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7898 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7899 NamedDecl *D = *I;
7900
7901 // Some of these decls (like enums) may have been pinned to the translation unit
7902 // for lack of a real context earlier. If so, remove from the translation unit
7903 // and reattach to the current context.
7904 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7905 // Is the decl actually in the context?
7906 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7907 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7908 if (*DI == D) {
7909 Context.getTranslationUnitDecl()->removeDecl(D);
7910 break;
7911 }
7912 }
7913 // Either way, reassign the lexical decl context to our FunctionDecl.
7914 D->setLexicalDeclContext(CurContext);
7915 }
7916
7917 // If the decl has a non-null name, make accessible in the current scope.
7918 if (!D->getName().empty())
7919 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7920
7921 // Similarly, dive into enums and fish their constants out, making them
7922 // accessible in this scope.
7923 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7924 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7925 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00007926 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00007927 }
7928 }
7929 }
7930
Richard Smith79a52e52012-04-17 22:30:01 +00007931 // Ensure that the function's exception specification is instantiated.
7932 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7933 ResolveExceptionSpec(D->getLocation(), FPT);
7934
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007935 // Checking attributes of current function definition
7936 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007937 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7938 if (DA && (!FD->getAttr<DLLExportAttr>())) {
7939 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00007940 // Microsoft accepts dllimport for functions defined within class scope.
7941 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00007942 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007943 Diag(FD->getLocation(),
7944 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7945 << "dllimport";
7946 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00007947 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00007948 }
7949
7950 // Visual C++ appears to not think this is an issue, so only issue
7951 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00007952 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007953 // If a symbol previously declared dllimport is later defined, the
7954 // attribute is ignored in subsequent references, and a warning is
7955 // emitted.
7956 Diag(FD->getLocation(),
7957 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00007958 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007959 }
7960 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00007961 // We want to attach documentation to original Decl (which might be
7962 // a function template).
7963 ActOnDocumentableDecl(D);
John McCall48871652010-08-21 09:40:31 +00007964 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00007965}
7966
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007967/// \brief Given the set of return statements within a function body,
7968/// compute the variables that are subject to the named return value
7969/// optimization.
7970///
7971/// Each of the variables that is subject to the named return value
7972/// optimization will be marked as NRVO variables in the AST, and any
7973/// return statement that has a marked NRVO variable as its NRVO candidate can
7974/// use the named return value optimization.
7975///
7976/// This function applies a very simplistic algorithm for NRVO: if every return
7977/// statement in the function has the same NRVO candidate, that candidate is
7978/// the NRVO variable.
7979///
7980/// FIXME: Employ a smarter algorithm that accounts for multiple return
7981/// statements and the lifetimes of the NRVO candidates. We should be able to
7982/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00007983void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00007984 ReturnStmt **Returns = Scope->Returns.data();
7985
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007986 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00007987 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007988 if (!Returns[I]->getNRVOCandidate())
7989 return;
7990
7991 if (!NRVOCandidate)
7992 NRVOCandidate = Returns[I]->getNRVOCandidate();
7993 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7994 return;
7995 }
7996
7997 if (NRVOCandidate)
7998 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7999}
8000
Richard Smith1ab34b32012-11-19 21:13:18 +00008001bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith9219d1b2012-11-27 21:31:01 +00008002 if (!Consumer.shouldSkipFunctionBody(D))
8003 return false;
8004
Richard Smith1ab34b32012-11-19 21:13:18 +00008005 if (isa<ObjCMethodDecl>(D))
8006 return true;
8007
8008 FunctionDecl *FD = 0;
8009 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
8010 FD = FTD->getTemplatedDecl();
8011 else
8012 FD = cast<FunctionDecl>(D);
8013
8014 // We cannot skip the body of a function (or function template) which is
8015 // constexpr, since we may need to evaluate its body in order to parse the
8016 // rest of the file.
8017 return !FD->isConstexpr();
8018}
8019
John McCallfaf5fb42010-08-26 23:41:50 +00008020Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008021 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00008022}
8023
John McCallb268a282010-08-23 23:25:46 +00008024Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
8025 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00008026 FunctionDecl *FD = 0;
8027 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
8028 if (FunTmpl)
8029 FD = FunTmpl->getTemplatedDecl();
8030 else
8031 FD = dyn_cast_or_null<FunctionDecl>(dcl);
8032
Ted Kremenek0b405322010-03-23 00:13:23 +00008033 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00008034 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00008035
Douglas Gregorc45a40a2009-08-22 00:34:47 +00008036 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00008037 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00008038
8039 // If the function implicitly returns zero (like 'main') or is naked,
8040 // don't complain about missing return statements.
8041 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00008042 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00008043
Francois Pichet3abc9b82011-05-11 02:14:46 +00008044 // MSVC permits the use of pure specifier (=0) on function definition,
8045 // defined at class scope, warn about this non standard construct.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008046 if (getLangOpts().MicrosoftExt && FD->isPure())
Francois Pichet3abc9b82011-05-11 02:14:46 +00008047 Diag(FD->getLocation(), diag::warn_pure_function_definition);
8048
Douglas Gregor88d292c2010-05-13 16:44:06 +00008049 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008050 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00008051 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
8052 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008053
8054 // If this is a constructor, we need a vtable.
8055 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
8056 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00008057
Jordan Rosed39e5f12012-07-02 21:19:23 +00008058 // Try to apply the named return value optimization. We have to check
8059 // if we can do this here because lambdas keep return statements around
8060 // to deduce an implicit return type.
8061 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
8062 !FD->isDependentContext())
8063 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00008064 }
8065
Douglas Gregor21f46922012-02-08 20:17:14 +00008066 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
8067 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00008068 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00008069 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00008070 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00008071 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008072 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00008073 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
8074 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00008075
8076 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00008077 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00008078 }
Jordan Rose2afd6612012-10-19 16:05:26 +00008079 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00008080 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
8081 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00008082 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00008083 }
Ted Kremenek5a201952009-02-07 01:47:29 +00008084 } else {
John McCall48871652010-08-21 09:40:31 +00008085 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00008086 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00008087
Jordan Rose2afd6612012-10-19 16:05:26 +00008088 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00008089 "This should only be set for ObjC methods, which should have been "
8090 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00008091
Chris Lattnere2473062007-05-28 06:28:18 +00008092 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00008093 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008094 // C++ constructors that have function-try-blocks can't have return
8095 // statements in the handlers of that block. (C++ [except.handle]p14)
8096 // Verify this.
8097 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
8098 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
8099
Richard Smithdef8bdb2011-08-12 18:44:32 +00008100 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00008101 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00008102 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00008103 !hasAnyUnrecoverableErrorsInThisFunction() &&
8104 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00008105 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00008106
John McCalldeb646e2010-08-04 01:04:25 +00008107 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
8108 if (!Destructor->getParent()->isDependentType())
8109 CheckDestructor(Destructor);
8110
John McCalla6309952010-03-16 21:39:52 +00008111 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8112 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00008113 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008114
8115 // If any errors have occurred, clear out any temporaries that may have
8116 // been leftover. This ensures that these temporaries won't be picked up for
8117 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00008118 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00008119 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00008120 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00008121 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00008122 // Since the body is valid, issue any analysis-based warnings that are
8123 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00008124 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00008125 }
8126
Richard Smith3607ffe2012-02-13 03:54:03 +00008127 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
8128 (!CheckConstexprFunctionDecl(FD) ||
8129 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00008130 FD->setInvalidDecl();
8131
John McCall28fc7092011-11-10 05:35:25 +00008132 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00008133 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00008134 assert(MaybeODRUseExprs.empty() &&
8135 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00008136 }
8137
John McCalle99d5f32010-03-25 22:08:03 +00008138 if (!IsInstantiation)
8139 PopDeclContext();
8140
Eli Friedman71c80552012-01-05 03:35:19 +00008141 PopFunctionScopeInfo(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00008142
Douglas Gregora7e3ea32009-11-15 07:07:58 +00008143 // If any errors have occurred, clear out any temporaries that may have
8144 // been leftover. This ensures that these temporaries won't be picked up for
8145 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00008146 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00008147 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00008148 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00008149
John McCall48871652010-08-21 09:40:31 +00008150 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00008151}
8152
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00008153
8154/// When we finish delayed parsing of an attribute, we must attach it to the
8155/// relevant Decl.
8156void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
8157 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00008158 // Always attach attributes to the underlying decl.
8159 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8160 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00008161 ProcessDeclAttributeList(S, D, Attrs.getList());
8162
8163 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
8164 if (Method->isStatic())
8165 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00008166}
8167
8168
Chris Lattnerac18be92006-11-20 06:49:47 +00008169/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
8170/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00008171NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00008172 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00008173 // Before we produce a declaration for an implicitly defined
8174 // function, see whether there was a locally-scoped declaration of
8175 // this name as a function or variable. If so, use that
8176 // (non-visible) declaration, and complain about it.
8177 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00008178 = findLocallyScopedExternalDecl(&II);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00008179 if (Pos != LocallyScopedExternalDecls.end()) {
8180 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
8181 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
8182 return Pos->second;
8183 }
8184
Chris Lattner00e26072008-05-05 21:18:06 +00008185 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00008186 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00008187 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00008188 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008189 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00008190 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00008191 else
Hans Wennborg70a13242011-12-08 15:56:07 +00008192 diag_id = diag::warn_implicit_function_decl;
8193 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00008194
Hans Wennborg70a13242011-12-08 15:56:07 +00008195 // Because typo correction is expensive, only do it if the implicit
8196 // function declaration is going to be treated as an error.
8197 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
8198 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00008199 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00008200 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00008201 LookupOrdinaryName, S, 0, Validator))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008202 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
8203 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00008204 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
Hans Wennborg70a13242011-12-08 15:56:07 +00008205
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00008206 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
8207 << FixItHint::CreateReplacement(Loc, CorrectedStr);
Hans Wennborg70a13242011-12-08 15:56:07 +00008208
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00008209 if (Func->getLocation().isValid()
8210 && !II.getName().startswith("__builtin_"))
8211 Diag(Func->getLocation(), diag::note_previous_decl)
8212 << CorrectedQuotedStr;
Hans Wennborg70a13242011-12-08 15:56:07 +00008213 }
Hans Wennborg2fb8b912011-12-06 09:46:12 +00008214 }
8215
Chris Lattnerac18be92006-11-20 06:49:47 +00008216 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00008217 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00008218 AttributeFactory attrFactory;
8219 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00008220 unsigned DiagID;
8221 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008222 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00008223 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00008224 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00008225 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00008226 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
8227 /*IsAmbiguous=*/false,
8228 /*RParenLoc=*/NoLoc,
8229 /*ArgInfo=*/0,
8230 /*NumArgs=*/0,
8231 /*EllipsisLoc=*/NoLoc,
8232 /*RParenLoc=*/NoLoc,
8233 /*TypeQuals=*/0,
8234 /*RefQualifierIsLvalueRef=*/true,
8235 /*RefQualifierLoc=*/NoLoc,
8236 /*ConstQualifierLoc=*/NoLoc,
8237 /*VolatileQualifierLoc=*/NoLoc,
8238 /*MutableLoc=*/NoLoc,
8239 EST_None,
8240 /*ESpecLoc=*/NoLoc,
8241 /*Exceptions=*/0,
8242 /*ExceptionRanges=*/0,
8243 /*NumExceptions=*/0,
8244 /*NoexceptExpr=*/0,
8245 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00008246 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00008247 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00008248 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00008249
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00008250 // Insert this function into translation-unit scope.
8251
8252 DeclContext *PrevDC = CurContext;
8253 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008254
John McCall48871652010-08-21 09:40:31 +00008255 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00008256 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00008257
8258 CurContext = PrevDC;
8259
Douglas Gregore711f702009-02-14 18:57:46 +00008260 AddKnownFunctionAttributes(FD);
8261
Steve Naroff3913ea42008-04-04 14:32:09 +00008262 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00008263}
8264
Douglas Gregore711f702009-02-14 18:57:46 +00008265/// \brief Adds any function attributes that we know a priori based on
8266/// the declaration of this function.
8267///
8268/// These attributes can apply both to implicitly-declared builtins
8269/// (like __builtin___printf_chk) or to library-declared functions
8270/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00008271///
8272/// We need to check for duplicate attributes both here and where user-written
8273/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00008274void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
8275 if (FD->isInvalidDecl())
8276 return;
8277
8278 // If this is a built-in function, map its builtin attributes to
8279 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00008280 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00008281 // Handle printf-formatting attributes.
8282 unsigned FormatIdx;
8283 bool HasVAListArg;
8284 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00008285 if (!FD->getAttr<FormatAttr>()) {
8286 const char *fmt = "printf";
8287 unsigned int NumParams = FD->getNumParams();
8288 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
8289 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
8290 fmt = "NSString";
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008291 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00008292 fmt, FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00008293 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00008294 }
Douglas Gregore711f702009-02-14 18:57:46 +00008295 }
Ted Kremenek5932c352010-07-16 02:11:15 +00008296 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
8297 HasVAListArg)) {
8298 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008299 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8300 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00008301 HasVAListArg ? 0 : FormatIdx+2));
8302 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00008303
8304 // Mark const if we don't care about errno and that is the only
8305 // thing preventing the function from being const. This allows
8306 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008307 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00008308 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00008309 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008310 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00008311 }
Mike Stumpca6c8752009-07-27 19:14:18 +00008312
Rafael Espindola2d21ab02011-10-12 19:51:18 +00008313 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
8314 !FD->getAttr<ReturnsTwiceAttr>())
8315 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00008316 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008317 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00008318 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008319 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00008320 }
8321
8322 IdentifierInfo *Name = FD->getIdentifier();
8323 if (!Name)
8324 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008325 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00008326 FD->getDeclContext()->isTranslationUnit()) ||
8327 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00008328 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00008329 LinkageSpecDecl::lang_c)) {
8330 // Okay: this could be a libc/libm/Objective-C function we know
8331 // about.
8332 } else
8333 return;
8334
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00008335 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00008336 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00008337 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00008338 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008339 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8340 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00008341 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00008342 }
Jordan Rose742c6072012-08-08 21:17:31 +00008343
8344 if (Name->isStr("__CFStringMakeConstantString")) {
8345 // We already have a __builtin___CFStringMakeConstantString,
8346 // but builds that use -fno-constant-cfstrings don't go through that.
8347 if (!FD->getAttr<FormatArgAttr>())
8348 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
8349 }
Douglas Gregore711f702009-02-14 18:57:46 +00008350}
Chris Lattner302b4be2006-11-19 02:31:38 +00008351
John McCall703a3f82009-10-24 08:00:42 +00008352TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00008353 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00008354 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00008355 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00008356
John McCallbcd03502009-12-07 02:54:59 +00008357 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00008358 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00008359 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00008360 }
8361
Chris Lattner18b19622007-01-22 07:39:13 +00008362 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00008363 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008364 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00008365 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00008366 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00008367 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00008368
John McCall04fcd0d2011-02-01 08:20:08 +00008369 // Bail out immediately if we have an invalid declaration.
8370 if (D.isInvalidType()) {
8371 NewTD->setInvalidDecl();
8372 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00008373 }
8374
Douglas Gregor41866812011-09-12 18:37:38 +00008375 if (D.getDeclSpec().isModulePrivateSpecified()) {
8376 if (CurContext->isFunctionOrMethod())
8377 Diag(NewTD->getLocation(), diag::err_module_private_local)
8378 << 2 << NewTD->getDeclName()
8379 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8380 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8381 else
8382 NewTD->setModulePrivate();
8383 }
Douglas Gregor26701a42011-09-09 02:06:17 +00008384
John McCall04fcd0d2011-02-01 08:20:08 +00008385 // C++ [dcl.typedef]p8:
8386 // If the typedef declaration defines an unnamed class (or
8387 // enum), the first typedef-name declared by the declaration
8388 // to be that class type (or enum type) is used to denote the
8389 // class type (or enum type) for linkage purposes only.
8390 // We need to check whether the type was declared in the declaration.
8391 switch (D.getDeclSpec().getTypeSpecType()) {
8392 case TST_enum:
8393 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00008394 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +00008395 case TST_union:
8396 case TST_class: {
8397 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
8398
8399 // Do nothing if the tag is not anonymous or already has an
8400 // associated typedef (from an earlier typedef in this decl group).
8401 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00008402 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00008403
8404 // A well-formed anonymous tag must always be a TUK_Definition.
8405 assert(tagFromDeclSpec->isThisDeclarationADefinition());
8406
8407 // The type must match the tag exactly; no qualifiers allowed.
8408 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
8409 break;
8410
8411 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00008412 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00008413 break;
8414 }
8415
8416 default:
8417 break;
8418 }
8419
Steve Narofff93b6722007-08-28 20:14:24 +00008420 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00008421}
8422
Douglas Gregord9034f02009-05-14 16:41:31 +00008423
Richard Smith4b38ded2012-03-14 23:13:10 +00008424/// \brief Check that this is a valid underlying type for an enum declaration.
8425bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
8426 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
8427 QualType T = TI->getType();
8428
8429 if (T->isDependentType() || T->isIntegralType(Context))
8430 return false;
8431
8432 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
8433 return true;
8434}
8435
8436/// Check whether this is a valid redeclaration of a previous enumeration.
8437/// \return true if the redeclaration was invalid.
8438bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
8439 QualType EnumUnderlyingTy,
8440 const EnumDecl *Prev) {
8441 bool IsFixed = !EnumUnderlyingTy.isNull();
8442
8443 if (IsScoped != Prev->isScoped()) {
8444 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
8445 << Prev->isScoped();
8446 Diag(Prev->getLocation(), diag::note_previous_use);
8447 return true;
8448 }
8449
8450 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +00008451 if (!EnumUnderlyingTy->isDependentType() &&
8452 !Prev->getIntegerType()->isDependentType() &&
8453 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +00008454 Prev->getIntegerType())) {
8455 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
8456 << EnumUnderlyingTy << Prev->getIntegerType();
8457 Diag(Prev->getLocation(), diag::note_previous_use);
8458 return true;
8459 }
8460 } else if (IsFixed != Prev->isFixed()) {
8461 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
8462 << Prev->isFixed();
8463 Diag(Prev->getLocation(), diag::note_previous_use);
8464 return true;
8465 }
8466
8467 return false;
8468}
8469
Joao Matosdc86f942012-08-31 18:45:21 +00008470/// \brief Get diagnostic %select index for tag kind for
8471/// redeclaration diagnostic message.
8472/// WARNING: Indexes apply to particular diagnostics only!
8473///
8474/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00008475static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +00008476 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00008477 case TTK_Struct: return 0;
8478 case TTK_Interface: return 1;
8479 case TTK_Class: return 2;
8480 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +00008481 }
Joao Matosdc86f942012-08-31 18:45:21 +00008482}
8483
8484/// \brief Determine if tag kind is a class-key compatible with
8485/// class for redeclaration (class, struct, or __interface).
8486///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008487/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +00008488static bool isClassCompatTagKind(TagTypeKind Tag)
8489{
8490 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
8491}
8492
Douglas Gregord9034f02009-05-14 16:41:31 +00008493/// \brief Determine whether a tag with a given kind is acceptable
8494/// as a redeclaration of the given tag declaration.
8495///
8496/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00008497bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00008498 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00008499 SourceLocation NewTagLoc,
8500 const IdentifierInfo &Name) {
8501 // C++ [dcl.type.elab]p3:
8502 // The class-key or enum keyword present in the
8503 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00008504 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00008505 // refers. This rule also applies to the form of
8506 // elaborated-type-specifier that declares a class-name or
8507 // friend class since it can be construed as referring to the
8508 // definition of the class. Thus, in any
8509 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00008510 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00008511 // used to refer to a union (clause 9), and either the class or
8512 // struct class-key shall be used to refer to a class (clause 9)
8513 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008514 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +00008515 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +00008516 if (OldTag == NewTag)
8517 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008518
Joao Matosdc86f942012-08-31 18:45:21 +00008519 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00008520 // Warn about the struct/class tag mismatch.
8521 bool isTemplate = false;
8522 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
8523 isTemplate = Record->getDescribedClassTemplate();
8524
Richard Trieucaa33d32011-06-10 03:11:26 +00008525 if (!ActiveTemplateInstantiations.empty()) {
8526 // In a template instantiation, do not offer fix-its for tag mismatches
8527 // since they usually mess up the template instead of fixing the problem.
8528 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +00008529 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8530 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +00008531 return true;
8532 }
8533
8534 if (isDefinition) {
8535 // On definitions, check previous tags and issue a fix-it for each
8536 // one that doesn't match the current tag.
8537 if (Previous->getDefinition()) {
8538 // Don't suggest fix-its for redefinitions.
8539 return true;
8540 }
8541
8542 bool previousMismatch = false;
8543 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
8544 E(Previous->redecls_end()); I != E; ++I) {
8545 if (I->getTagKind() != NewTag) {
8546 if (!previousMismatch) {
8547 previousMismatch = true;
8548 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +00008549 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8550 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +00008551 }
8552 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +00008553 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +00008554 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +00008555 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +00008556 }
8557 }
8558 return true;
8559 }
8560
8561 // Check for a previous definition. If current tag and definition
8562 // are same type, do nothing. If no definition, but disagree with
8563 // with previous tag type, give a warning, but no fix-it.
8564 const TagDecl *Redecl = Previous->getDefinition() ?
8565 Previous->getDefinition() : Previous;
8566 if (Redecl->getTagKind() == NewTag) {
8567 return true;
8568 }
8569
Douglas Gregord9034f02009-05-14 16:41:31 +00008570 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +00008571 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8572 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +00008573 Diag(Redecl->getLocation(), diag::note_previous_use);
8574
8575 // If there is a previous defintion, suggest a fix-it.
8576 if (Previous->getDefinition()) {
8577 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +00008578 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +00008579 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +00008580 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +00008581 }
8582
Douglas Gregord9034f02009-05-14 16:41:31 +00008583 return true;
8584 }
8585 return false;
8586}
8587
Steve Naroff30d242c2007-09-15 18:49:24 +00008588/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00008589/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00008590/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00008591/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00008592Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00008593 SourceLocation KWLoc, CXXScopeSpec &SS,
8594 IdentifierInfo *Name, SourceLocation NameLoc,
8595 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00008596 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +00008597 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00008598 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +00008599 SourceLocation ScopedEnumKWLoc,
8600 bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00008601 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008602 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008603 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +00008604 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00008605 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00008606 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008607
Douglas Gregord6ab8742009-05-28 23:31:59 +00008608 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00008609 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +00008610 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +00008611
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008612 // FIXME: Check explicit specializations more carefully.
8613 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008614 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00008615
8616 // We only need to do this matching if we have template parameters
8617 // or a scope specifier, which also conveniently avoids this work
8618 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00008619 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00008620 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00008621 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008622 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008623 TemplateParameterLists.data(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00008624 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00008625 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008626 isExplicitSpecialization,
8627 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00008628 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00008629 // This is a declaration or definition of a class template (which may
8630 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00008631
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008632 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00008633 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008634
Douglas Gregore93e46c2009-07-22 23:48:44 +00008635 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00008636 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00008637 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008638 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00008639 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008640 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008641 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +00008642 return Result.get();
8643 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008644 // The "template<>" header is extraneous.
8645 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008646 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008647 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00008648 }
Mike Stump11289f42009-09-09 15:08:12 +00008649 }
8650 }
8651
Douglas Gregor0bf31402010-10-08 23:50:27 +00008652 // Figure out the underlying type if this a enum declaration. We need to do
8653 // this early, because it's needed to detect if this is an incompatible
8654 // redeclaration.
8655 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8656
8657 if (Kind == TTK_Enum) {
8658 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8659 // No underlying type explicitly specified, or we failed to parse the
8660 // type, default to int.
8661 EnumUnderlying = Context.IntTy.getTypePtr();
8662 else if (UnderlyingType.get()) {
8663 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8664 // integral type; any cv-qualification is ignored.
8665 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +00008666 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008667 EnumUnderlying = TI;
8668
Richard Smith4b38ded2012-03-14 23:13:10 +00008669 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +00008670 // Recover by falling back to int.
8671 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008672
Richard Smith4b38ded2012-03-14 23:13:10 +00008673 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008674 UPPC_FixedUnderlyingType))
8675 EnumUnderlying = Context.IntTy.getTypePtr();
8676
David Blaikiebbafb8a2012-03-11 07:00:24 +00008677 } else if (getLangOpts().MicrosoftMode)
Francois Picheta3108062010-10-18 15:01:13 +00008678 // Microsoft enums are always of int type.
8679 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008680 }
8681
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008682 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008683 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00008684 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00008685
Chandler Carrutha419dbb2010-03-01 21:17:36 +00008686 RedeclarationKind Redecl = ForRedeclaration;
8687 if (TUK == TUK_Friend || TUK == TUK_Reference)
8688 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00008689
8690 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00008691
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008692 if (Name && SS.isNotEmpty()) {
8693 // We have a nested-name tag ('struct foo::bar').
8694
8695 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008696 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008697 Name = 0;
8698 goto CreateNewDecl;
8699 }
8700
John McCall7f41d982009-09-11 04:59:25 +00008701 // If this is a friend or a reference to a class in a dependent
8702 // context, don't try to make a decl for it.
8703 if (TUK == TUK_Friend || TUK == TUK_Reference) {
8704 DC = computeDeclContext(SS, false);
8705 if (!DC) {
8706 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00008707 return 0;
John McCall7f41d982009-09-11 04:59:25 +00008708 }
John McCall0b66eb32010-05-01 00:40:08 +00008709 } else {
8710 DC = computeDeclContext(SS, true);
8711 if (!DC) {
8712 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8713 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008714 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00008715 }
John McCall7f41d982009-09-11 04:59:25 +00008716 }
8717
John McCall0b66eb32010-05-01 00:40:08 +00008718 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00008719 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008720
Douglas Gregor8761da52009-02-03 00:34:39 +00008721 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008722 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00008723 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00008724
John McCall1f82f242009-11-18 22:49:29 +00008725 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008726 return 0;
John McCall6538c932009-10-10 05:48:19 +00008727
John McCall1f82f242009-11-18 22:49:29 +00008728 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00008729 // Name lookup did not find anything. However, if the
8730 // nested-name-specifier refers to the current instantiation,
8731 // and that current instantiation has any dependent base
8732 // classes, we might find something at instantiation time: treat
8733 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00008734 // But this only makes any sense for reference-like lookups.
8735 if (Previous.wasNotFoundInCurrentInstantiation() &&
8736 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00008737 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00008738 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00008739 }
8740
8741 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00008742 Diag(NameLoc, diag::err_not_tag_in_scope)
8743 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008744 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008745 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008746 goto CreateNewDecl;
8747 }
Chris Lattnerd9773512009-01-21 02:38:50 +00008748 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008749 // If this is a named struct, check to see if there was a previous forward
8750 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00008751 // FIXME: We're looking into outer scopes here, even when we
8752 // shouldn't be. Doing so can result in ambiguities that we
8753 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00008754 LookupName(Previous, S);
8755
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00008756 if (Previous.isAmbiguous() &&
8757 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00008758 LookupResult::Filter F = Previous.makeFilter();
8759 while (F.hasNext()) {
8760 NamedDecl *ND = F.next();
8761 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8762 F.erase();
8763 }
8764 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00008765 }
8766
John McCall1f82f242009-11-18 22:49:29 +00008767 // Note: there used to be some attempt at recovery here.
8768 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008769 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008770
David Blaikiebbafb8a2012-03-11 07:00:24 +00008771 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008772 // FIXME: This makes sure that we ignore the contexts associated
8773 // with C structs, unions, and enums when looking for a matching
8774 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00008775 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008776 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8777 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008778 }
Douglas Gregor009f6992010-09-16 23:58:57 +00008779 } else if (S->isFunctionPrototypeScope()) {
8780 // If this is an enum declaration in function prototype scope, set its
8781 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +00008782 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +00008783 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008784 }
8785
John McCall1f82f242009-11-18 22:49:29 +00008786 if (Previous.isSingleResult() &&
8787 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00008788 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00008789 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00008790 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00008791 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00008792 }
8793
David Blaikiebbafb8a2012-03-11 07:00:24 +00008794 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008795 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008796 // This is a declaration of or a reference to "std::bad_alloc".
8797 isStdBadAlloc = true;
8798
John McCall1f82f242009-11-18 22:49:29 +00008799 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008800 // std::bad_alloc has been implicitly declared (but made invisible to
8801 // name lookup). Fill in this implicit declaration as the previous
8802 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008803 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00008804 }
8805 }
John McCall1f82f242009-11-18 22:49:29 +00008806
John McCalle9eaf8e2010-03-25 21:28:06 +00008807 // If we didn't find a previous declaration, and this is a reference
8808 // (or friend reference), move to the correct scope. In C++, we
8809 // also need to do a redeclaration lookup there, just in case
8810 // there's a shadow friend decl.
8811 if (Name && Previous.empty() &&
8812 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8813 if (Invalid) goto CreateNewDecl;
8814 assert(SS.isEmpty());
8815
8816 if (TUK == TUK_Reference) {
8817 // C++ [basic.scope.pdecl]p5:
8818 // -- for an elaborated-type-specifier of the form
8819 //
8820 // class-key identifier
8821 //
8822 // if the elaborated-type-specifier is used in the
8823 // decl-specifier-seq or parameter-declaration-clause of a
8824 // function defined in namespace scope, the identifier is
8825 // declared as a class-name in the namespace that contains
8826 // the declaration; otherwise, except as a friend
8827 // declaration, the identifier is declared in the smallest
8828 // non-class, non-function-prototype scope that contains the
8829 // declaration.
8830 //
8831 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8832 // C structs and unions.
8833 //
8834 // It is an error in C++ to declare (rather than define) an enum
8835 // type, including via an elaborated type specifier. We'll
8836 // diagnose that later; for now, declare the enum in the same
8837 // scope as we would have picked for any other tag type.
8838 //
8839 // GNU C also supports this behavior as part of its incomplete
8840 // enum types extension, while GNU C++ does not.
8841 //
8842 // Find the context where we'll be declaring the tag.
8843 // FIXME: We would like to maintain the current DeclContext as the
8844 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +00008845 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +00008846 SearchDC = SearchDC->getParent();
8847
8848 // Find the scope where we'll be declaring the tag.
8849 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008850 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +00008851 S->isFunctionPrototypeScope()) ||
8852 ((S->getFlags() & Scope::DeclScope) == 0) ||
8853 (S->getEntity() &&
8854 ((DeclContext *)S->getEntity())->isTransparentContext()))
8855 S = S->getParent();
8856 } else {
8857 assert(TUK == TUK_Friend);
8858 // C++ [namespace.memdef]p3:
8859 // If a friend declaration in a non-local class first declares a
8860 // class or function, the friend class or function is a member of
8861 // the innermost enclosing namespace.
8862 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00008863 }
8864
John McCalle87beb22010-04-23 18:46:30 +00008865 // In C++, we need to do a redeclaration lookup to properly
8866 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008867 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +00008868 Previous.setRedeclarationKind(ForRedeclaration);
8869 LookupQualifiedName(Previous, SearchDC);
8870 }
8871 }
8872
John McCall1f82f242009-11-18 22:49:29 +00008873 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00008874 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00008875
8876 // It's okay to have a tag decl in the same scope as a typedef
8877 // which hides a tag decl in the same scope. Finding this
8878 // insanity with a redeclaration lookup can only actually happen
8879 // in C++.
8880 //
8881 // This is also okay for elaborated-type-specifiers, which is
8882 // technically forbidden by the current standard but which is
8883 // okay according to the likely resolution of an open issue;
8884 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +00008885 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00008886 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00008887 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8888 TagDecl *Tag = TT->getDecl();
8889 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008890 Tag->getDeclContext()->getRedeclContext()
8891 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00008892 PrevDecl = Tag;
8893 Previous.clear();
8894 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00008895 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00008896 }
8897 }
8898 }
8899 }
8900
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008901 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00008902 // If this is a use of a previous tag, or if the tag is already declared
8903 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008904 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00008905 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00008906 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00008907 // Make sure that this wasn't declared as an enum and now used as a
8908 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00008909 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8910 TUK == TUK_Definition, KWLoc,
8911 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00008912 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00008913 = (PrevTagDecl->getTagKind() != TTK_Enum &&
8914 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00008915 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00008916 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00008917 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00008918 << FixItHint::CreateReplacement(SourceRange(KWLoc),
8919 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00008920 else
8921 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00008922 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00008923
Mike Stump11289f42009-09-09 15:08:12 +00008924 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00008925 Kind = PrevTagDecl->getTagKind();
8926 else {
8927 // Recover by making this an anonymous redefinition.
8928 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008929 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00008930 Invalid = true;
8931 }
8932 }
8933
Douglas Gregor0bf31402010-10-08 23:50:27 +00008934 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8935 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8936
Richard Smith0f8ee222012-01-10 01:33:14 +00008937 // If this is an elaborated-type-specifier for a scoped enumeration,
8938 // the 'class' keyword is not necessary and not permitted.
8939 if (TUK == TUK_Reference || TUK == TUK_Friend) {
8940 if (ScopedEnum)
8941 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8942 << PrevEnum->isScoped()
8943 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8944 return PrevTagDecl;
8945 }
8946
Richard Smith4b38ded2012-03-14 23:13:10 +00008947 QualType EnumUnderlyingTy;
8948 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8949 EnumUnderlyingTy = TI->getType();
8950 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8951 EnumUnderlyingTy = QualType(T, 0);
8952
Douglas Gregor0bf31402010-10-08 23:50:27 +00008953 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +00008954 // returning the previous declaration, unless this is a definition,
8955 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +00008956 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8957 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +00008958 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +00008959 }
8960
Douglas Gregor170512f2009-04-01 23:51:29 +00008961 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008962 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00008963
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008964 // FIXME: In the future, return a variant or some other clue
8965 // for the consumer of this Decl to know it doesn't own it.
8966 // For our current ASTs this shouldn't be a problem, but will
8967 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00008968 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008969 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00008970 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008971
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008972 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00008973 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008974 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008975 // If we're defining a specialization and the previous definition
8976 // is from an implicit instantiation, don't emit an error
8977 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +00008978 bool IsExplicitSpecializationAfterInstantiation = false;
8979 if (isExplicitSpecialization) {
8980 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8981 IsExplicitSpecializationAfterInstantiation =
8982 RD->getTemplateSpecializationKind() !=
8983 TSK_ExplicitSpecialization;
8984 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8985 IsExplicitSpecializationAfterInstantiation =
8986 ED->getTemplateSpecializationKind() !=
8987 TSK_ExplicitSpecialization;
8988 }
8989
8990 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +00008991 // A redeclaration in function prototype scope in C isn't
8992 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008993 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +00008994 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8995 else
8996 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008997 Diag(Def->getLocation(), diag::note_previous_definition);
8998 // If this is a redefinition, recover by making this
8999 // struct be anonymous, which will make any later
9000 // references get the previous definition.
9001 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00009002 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00009003 Invalid = true;
9004 }
Douglas Gregordee1be82009-01-17 00:42:38 +00009005 } else {
9006 // If the type is currently being defined, complain
9007 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00009008 const TagType *Tag
9009 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00009010 if (Tag->isBeingDefined()) {
9011 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00009012 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00009013 diag::note_previous_definition);
9014 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00009015 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00009016 Invalid = true;
9017 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009018 }
Douglas Gregordee1be82009-01-17 00:42:38 +00009019
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009020 // Okay, this is definition of a previously declared or referenced
9021 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00009022 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00009023 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009024 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00009025 // have a definition. Just create a new decl.
9026
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009027 } else {
9028 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00009029 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009030 // new decl/type. We set PrevDecl to NULL so that the entities
9031 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00009032 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00009033 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009034 // If we get here, we're going to create a new Decl. If PrevDecl
9035 // is non-NULL, it's a definition of the tag declared by
9036 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00009037
9038
9039 // Otherwise, PrevDecl is not a tag, but was found with tag
9040 // lookup. This is only actually possible in C++, where a few
9041 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00009042 } else {
John McCalle87beb22010-04-23 18:46:30 +00009043 // Use a better diagnostic if an elaborated-type-specifier
9044 // found the wrong kind of type on the first
9045 // (non-redeclaration) lookup.
9046 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
9047 !Previous.isForRedeclaration()) {
9048 unsigned Kind = 0;
9049 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00009050 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9051 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00009052 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
9053 Diag(PrevDecl->getLocation(), diag::note_declared_at);
9054 Invalid = true;
9055
9056 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00009057 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
9058 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00009059 // do nothing
9060
9061 // Diagnose implicit declarations introduced by elaborated types.
9062 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
9063 unsigned Kind = 0;
9064 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00009065 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9066 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00009067 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
9068 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9069 Invalid = true;
9070
9071 // Otherwise it's a declaration. Call out a particularly common
9072 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00009073 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9074 unsigned Kind = 0;
9075 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00009076 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00009077 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00009078 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9079 Invalid = true;
9080
9081 // Otherwise, diagnose.
9082 } else {
9083 // The tag name clashes with something else in the target scope,
9084 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009085 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00009086 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00009087 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00009088 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00009089 }
John McCalle87beb22010-04-23 18:46:30 +00009090
9091 // The existing declaration isn't relevant to us; we're in a
9092 // new scope, so clear out the previous declaration.
9093 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00009094 }
Chris Lattner18b19622007-01-22 07:39:13 +00009095 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00009096
Chris Lattner438e5012008-12-17 07:13:27 +00009097CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00009098
John McCall1f82f242009-11-18 22:49:29 +00009099 TagDecl *PrevDecl = 0;
9100 if (Previous.isSingleResult())
9101 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
9102
Chris Lattnerbf0b7982007-01-23 04:27:41 +00009103 // If there is an identifier, use the location of the identifier as the
9104 // location of the decl, otherwise use the location of the struct/union
9105 // keyword.
9106 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00009107
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009108 // Otherwise, create a new declaration. If there is a previous
9109 // declaration of the same entity, the two will be linked via
9110 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00009111 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00009112
Douglas Gregor0bf31402010-10-08 23:50:27 +00009113 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00009114 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00009115 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9116 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00009117 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00009118 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00009119 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00009120 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00009121 if (TUK != TUK_Definition && !Invalid) {
9122 TagDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009123 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00009124 // C++0x: 7.2p2: opaque-enum-declaration.
9125 // Conflicts are diagnosed above. Do nothing.
9126 }
9127 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00009128 Diag(Loc, diag::ext_forward_ref_enum_def)
9129 << New;
9130 Diag(Def->getLocation(), diag::note_previous_definition);
9131 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00009132 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009133 if (getLangOpts().MicrosoftMode)
Francois Pichet488b4a72010-09-12 05:06:55 +00009134 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009135 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +00009136 DiagID = diag::err_forward_ref_enum;
9137 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00009138
9139 // If this is a forward-declared reference to an enumeration, make a
9140 // note of it; we won't actually be introducing the declaration into
9141 // the declaration context.
9142 if (TUK == TUK_Reference)
9143 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00009144 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00009145 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00009146
9147 if (EnumUnderlying) {
9148 EnumDecl *ED = cast<EnumDecl>(New);
9149 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9150 ED->setIntegerTypeSourceInfo(TI);
9151 else
9152 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
9153 ED->setPromotionType(ED->getIntegerType());
9154 }
9155
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00009156 } else {
9157 // struct/union/class
9158
Chris Lattner776fac82007-06-09 00:53:06 +00009159 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9160 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009161 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00009162 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00009163 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009164 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00009165
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00009166 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00009167 StdBadAlloc = cast<CXXRecordDecl>(New);
9168 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00009169 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009170 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009171 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009172
John McCall3e11ebe2010-03-15 10:12:16 +00009173 // Maybe add qualifier info.
9174 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00009175 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00009176 // If this is either a declaration or a definition, check the
9177 // nested-name-specifier against the current context. We don't do this
9178 // for explicit specializations, because they have similar checking
9179 // (with more specific diagnostics) in the call to
9180 // CheckMemberSpecialization, below.
9181 if (!isExplicitSpecialization &&
9182 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
9183 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
9184 Invalid = true;
9185
Douglas Gregor14454802011-02-25 02:25:35 +00009186 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00009187 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00009188 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00009189 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009190 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00009191 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00009192 }
9193 else
9194 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00009195 }
9196
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00009197 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
9198 // Add alignment attributes if necessary; these attributes are checked when
9199 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009200 //
9201 // It is important for implementing the correct semantics that this
9202 // happen here (in act on tag decl). The #pragma pack stack is
9203 // maintained as a result of parser callbacks which can occur at
9204 // many points during the parsing of a struct declaration (because
9205 // the #pragma tokens are effectively skipped over during the
9206 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +00009207 if (TUK == TUK_Definition) {
9208 AddAlignmentAttributesForRecord(RD);
9209 AddMsStructLayoutForRecord(RD);
9210 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009211 }
9212
Douglas Gregor21823bf2011-12-20 18:11:52 +00009213 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00009214 if (isExplicitSpecialization)
9215 Diag(New->getLocation(), diag::err_module_private_specialization)
9216 << 2
9217 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +00009218 // __module_private__ does not apply to local classes. However, we only
9219 // diagnose this as an error when the declaration specifiers are
9220 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +00009221 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +00009222 New->setModulePrivate();
9223 }
9224
Douglas Gregorbbe8f462009-10-08 15:14:33 +00009225 // If this is a specialization of a member class (of a class template),
9226 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00009227 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00009228 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00009229
Douglas Gregordee1be82009-01-17 00:42:38 +00009230 if (Invalid)
9231 New->setInvalidDecl();
9232
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009233 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00009234 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009235
Douglas Gregordee1be82009-01-17 00:42:38 +00009236 // If we're declaring or defining a tag in function prototype scope
9237 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009238 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +00009239 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
9240
Douglas Gregorc811d8f2008-12-15 16:32:14 +00009241 // Set the lexical context. If the tag has a C++ scope specifier, the
9242 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00009243 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00009244
John McCallaa74a0c2009-08-28 07:59:38 +00009245 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00009246 // In Microsoft mode, a friend declaration also acts as a forward
9247 // declaration so we always pass true to setObjectOfFriendDecl to make
9248 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00009249 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00009250 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00009251 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +00009252
Anders Carlsson5558ca12009-03-26 01:19:02 +00009253 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00009254 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00009255 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00009256
John McCall9bb74a52009-07-31 02:45:11 +00009257 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00009258 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00009259
Chris Lattner18b19622007-01-22 07:39:13 +00009260 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00009261 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00009262 // We might be replacing an existing declaration in the lookup tables;
9263 // if so, borrow its access specifier.
9264 if (PrevDecl)
9265 New->setAccess(PrevDecl->getAccess());
9266
Sebastian Redl50c68252010-08-31 00:36:30 +00009267 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00009268 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +00009269 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00009270 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9271 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00009272 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00009273 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00009274 PushOnScopeChains(New, S, !IsForwardReference);
9275 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +00009276 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +00009277
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00009278 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009279 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00009280 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00009281
Douglas Gregor27821ce2009-07-07 16:35:42 +00009282 // If this is the C FILE type, notify the AST context.
9283 if (IdentifierInfo *II = New->getIdentifier())
9284 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00009285 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00009286 II->isStr("FILE"))
9287 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00009288
James Molloy6f8780b2012-02-29 10:24:19 +00009289 // If we were in function prototype scope (and not in C++ mode), add this
9290 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009291 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +00009292 InFunctionDeclarator && Name)
9293 DeclsInPrototypeScope.push_back(New);
9294
Rafael Espindolac67f2232012-05-10 02:50:16 +00009295 if (PrevDecl)
9296 mergeDeclAttributes(New, PrevDecl);
9297
Rafael Espindolae3a14bb2012-07-17 15:14:47 +00009298 // If there's a #pragma GCC visibility in scope, set the visibility of this
9299 // record.
9300 AddPushedVisibilityAttribute(New);
9301
Douglas Gregord6ab8742009-05-28 23:31:59 +00009302 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00009303 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00009304}
Chris Lattner1300fb92007-01-23 23:42:53 +00009305
John McCall48871652010-08-21 09:40:31 +00009306void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00009307 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00009308 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00009309
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009310 // Enter the tag context.
9311 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009312
9313 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +00009314
9315 // If there's a #pragma GCC visibility in scope, set the visibility of this
9316 // record.
9317 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00009318}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009319
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009320Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009321 assert(isa<ObjCContainerDecl>(IDecl) &&
9322 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
9323 DeclContext *OCD = cast<DeclContext>(IDecl);
9324 assert(getContainingDC(OCD) == CurContext &&
9325 "The next DeclContext should be lexically contained in the current one.");
9326 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009327 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009328}
9329
John McCall48871652010-08-21 09:40:31 +00009330void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00009331 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00009332 SourceLocation LBraceLoc) {
9333 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00009334 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009335
John McCall1c7e6ec2009-12-20 07:58:13 +00009336 FieldCollector->StartClass();
9337
9338 if (!Record->getIdentifier())
9339 return;
9340
Anders Carlsson30f29442011-03-25 14:31:08 +00009341 if (FinalLoc.isValid())
9342 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00009343
John McCall1c7e6ec2009-12-20 07:58:13 +00009344 // C++ [class]p2:
9345 // [...] The class-name is also inserted into the scope of the
9346 // class itself; this is known as the injected-class-name. For
9347 // purposes of access checking, the injected-class-name is treated
9348 // as if it were a public member name.
9349 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00009350 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
9351 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00009352 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00009353 /*PrevDecl=*/0,
9354 /*DelayTypeCreation=*/true);
9355 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00009356 InjectedClassName->setImplicit();
9357 InjectedClassName->setAccess(AS_public);
9358 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
9359 InjectedClassName->setDescribedClassTemplate(Template);
9360 PushOnScopeChains(InjectedClassName, S);
9361 assert(InjectedClassName->isInjectedClassName() &&
9362 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009363}
9364
John McCall48871652010-08-21 09:40:31 +00009365void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00009366 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00009367 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00009368 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00009369 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009370
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00009371 // Make sure we "complete" the definition even it is invalid.
9372 if (Tag->isBeingDefined()) {
9373 assert(Tag->isInvalidDecl() && "We should already have completed it");
9374 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9375 RD->completeDefinition();
9376 }
9377
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009378 if (isa<CXXRecordDecl>(Tag))
9379 FieldCollector->FinishClass();
9380
9381 // Exit this scope of this tag's definition.
9382 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00009383
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009384 // Notify the consumer that we've defined a tag.
9385 Consumer.HandleTagDeclDefinition(Tag);
9386}
Chris Lattner535b8302008-06-21 19:39:06 +00009387
Fariborz Jahanian4327b322011-08-29 17:33:12 +00009388void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009389 // Exit this scope of this interface definition.
9390 PopDeclContext();
9391}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009392
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +00009393void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +00009394 assert(DC == CurContext && "Mismatch of container contexts");
9395 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009396 ActOnObjCContainerFinishDefinition();
9397}
9398
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +00009399void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
9400 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009401 OriginalLexicalContext = 0;
9402}
9403
John McCall48871652010-08-21 09:40:31 +00009404void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00009405 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00009406 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00009407 Tag->setInvalidDecl();
9408
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00009409 // Make sure we "complete" the definition even it is invalid.
9410 if (Tag->isBeingDefined()) {
9411 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9412 RD->completeDefinition();
9413 }
9414
John McCall71ba5f22010-03-17 19:25:57 +00009415 // We're undoing ActOnTagStartDefinition here, not
9416 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
9417 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00009418
9419 PopDeclContext();
9420}
9421
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009422// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +00009423ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
9424 IdentifierInfo *FieldName,
9425 QualType FieldTy, Expr *BitWidth,
9426 bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +00009427 // Default to true; that shouldn't confuse checks for emptiness
9428 if (ZeroWidth)
9429 *ZeroWidth = true;
9430
Chris Lattner73bf7b42009-03-05 22:45:59 +00009431 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00009432 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00009433 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00009434 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00009435 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +00009436 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009437 if (FieldName)
9438 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
9439 << FieldName << FieldTy << BitWidth->getSourceRange();
9440 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
9441 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00009442 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
9443 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +00009444 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +00009445
9446 // If the bit-width is type- or value-dependent, don't try to check
9447 // it now.
9448 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +00009449 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009450
Anders Carlsson5df391e2008-12-06 20:33:04 +00009451 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00009452 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
9453 if (ICE.isInvalid())
9454 return ICE;
9455 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +00009456
Eli Friedmanc96d4962009-08-15 21:55:26 +00009457 if (Value != 0 && ZeroWidth)
9458 *ZeroWidth = false;
9459
Chris Lattner81ed6802008-12-12 04:56:04 +00009460 // Zero-width bitfield is ok for anonymous field.
9461 if (Value == 0 && FieldName)
9462 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00009463
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009464 if (Value.isSigned() && Value.isNegative()) {
9465 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00009466 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009467 << FieldName << Value.toString(10);
9468 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
9469 << Value.toString(10);
9470 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009471
Douglas Gregor1efa4372009-03-11 18:59:21 +00009472 if (!FieldTy->isDependentType()) {
9473 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009474 if (Value.getZExtValue() > TypeSize) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009475 if (!getLangOpts().CPlusPlus) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00009476 if (FieldName)
9477 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
9478 << FieldName << (unsigned)Value.getZExtValue()
9479 << (unsigned)TypeSize;
9480
9481 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
9482 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9483 }
9484
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009485 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00009486 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
9487 << FieldName << (unsigned)Value.getZExtValue()
9488 << (unsigned)TypeSize;
9489 else
9490 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
9491 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009492 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00009493 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009494
Richard Smithf4c51d92012-02-04 09:53:13 +00009495 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +00009496}
9497
Richard Smith938f40b2011-06-11 17:19:42 +00009498/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00009499/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00009500Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00009501 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00009502 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00009503 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +00009504 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +00009505 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00009506}
9507
9508/// HandleField - Analyze a field of a C struct or a C++ data member.
9509///
9510FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
9511 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +00009512 Declarator &D, Expr *BitWidth,
9513 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009514 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00009515 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00009516 SourceLocation Loc = DeclStart;
9517 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00009518
John McCall8cb7bdf2010-06-04 23:28:52 +00009519 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9520 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009521 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00009522 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00009523
Douglas Gregora02a72a2010-12-15 23:18:36 +00009524 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9525 UPPC_DataMemberType)) {
9526 D.setInvalidType();
9527 T = Context.IntTy;
9528 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
9529 }
9530 }
9531
Eli Friedman574c7452009-04-07 19:37:57 +00009532 DiagnoseFunctionSpecifiers(D);
9533
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009534 if (D.getDeclSpec().isThreadSpecified())
9535 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00009536 if (D.getDeclSpec().isConstexprSpecified())
9537 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
9538 << 2;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00009539
9540 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +00009541 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00009542 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
9543 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +00009544 switch (Previous.getResultKind()) {
9545 case LookupResult::Found:
9546 case LookupResult::FoundUnresolvedValue:
9547 PrevDecl = Previous.getAsSingle<NamedDecl>();
9548 break;
9549
9550 case LookupResult::FoundOverloaded:
9551 PrevDecl = Previous.getRepresentativeDecl();
9552 break;
9553
9554 case LookupResult::NotFound:
9555 case LookupResult::NotFoundInCurrentInstantiation:
9556 case LookupResult::Ambiguous:
9557 break;
9558 }
9559 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +00009560
9561 if (PrevDecl && PrevDecl->isTemplateParameter()) {
9562 // Maybe we will complain about the shadowed template parameter.
9563 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9564 // Just pretend that we didn't see the previous declaration.
9565 PrevDecl = 0;
9566 }
9567
Douglas Gregor1efa4372009-03-11 18:59:21 +00009568 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
9569 PrevDecl = 0;
9570
Steve Naroff5ec6ff72009-07-14 14:58:18 +00009571 bool Mutable
9572 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009573 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +00009574 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +00009575 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +00009576 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00009577
9578 if (NewFD->isInvalidDecl())
9579 Record->setInvalidDecl();
9580
Douglas Gregor3baa6702011-09-12 16:11:24 +00009581 if (D.getDeclSpec().isModulePrivateSpecified())
9582 NewFD->setModulePrivate();
9583
Douglas Gregor1efa4372009-03-11 18:59:21 +00009584 if (NewFD->isInvalidDecl() && PrevDecl) {
9585 // Don't introduce NewFD into scope; there's already something
9586 // with the same name in the same scope.
9587 } else if (II) {
9588 PushOnScopeChains(NewFD, S);
9589 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009590 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009591
9592 return NewFD;
9593}
9594
9595/// \brief Build a new FieldDecl and check its well-formedness.
9596///
9597/// This routine builds a new FieldDecl given the fields name, type,
9598/// record, etc. \p PrevDecl should refer to any previous declaration
9599/// with the same name and in the same scope as the field to be
9600/// created.
9601///
9602/// \returns a new FieldDecl.
9603///
Mike Stump11289f42009-09-09 15:08:12 +00009604/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00009605FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00009606 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00009607 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +00009608 bool Mutable, Expr *BitWidth,
9609 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00009610 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009611 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00009612 Declarator *D) {
9613 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00009614 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009615 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009616
Douglas Gregor1efa4372009-03-11 18:59:21 +00009617 // If we receive a broken type, recover by assuming 'int' and
9618 // marking this declaration as invalid.
9619 if (T.isNull()) {
9620 InvalidDecl = true;
9621 T = Context.IntTy;
9622 }
9623
Eli Friedmand0e8de22009-12-07 00:22:08 +00009624 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00009625 if (!EltTy->isDependentType()) {
9626 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9627 // Fields of incomplete type force their record to be invalid.
9628 Record->setInvalidDecl();
9629 InvalidDecl = true;
9630 } else {
9631 NamedDecl *Def;
9632 EltTy->isIncompleteType(&Def);
9633 if (Def && Def->isInvalidDecl()) {
9634 Record->setInvalidDecl();
9635 InvalidDecl = true;
9636 }
9637 }
John McCall2677e102010-08-16 23:42:35 +00009638 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00009639
Steve Naroff8eeeb132007-05-08 21:09:37 +00009640 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9641 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00009642 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00009643 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009644 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00009645
9646 TypeSourceInfo *FixedTInfo =
9647 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
9648 SizeIsNegative,
9649 Oversized);
9650 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00009651 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00009652 TInfo = FixedTInfo;
9653 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +00009654 } else {
9655 if (SizeIsNegative)
9656 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009657 else if (Oversized.getBoolValue())
9658 Diag(Loc, diag::err_array_too_large)
9659 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009660 else
9661 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009662 InvalidDecl = true;
9663 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00009664 }
Mike Stump11289f42009-09-09 15:08:12 +00009665
Anders Carlsson576cc6f2009-03-22 20:18:17 +00009666 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00009667 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9668 diag::err_abstract_type_in_decl,
9669 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00009670 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00009671
Eli Friedmanc96d4962009-08-15 21:55:26 +00009672 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00009673 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +00009674 if (!InvalidDecl && BitWidth) {
9675 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9676 if (!BitWidth) {
9677 InvalidDecl = true;
9678 BitWidth = 0;
9679 ZeroWidth = false;
9680 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009681 }
Mike Stump11289f42009-09-09 15:08:12 +00009682
John McCallb1cd7da2010-06-04 08:34:12 +00009683 // Check that 'mutable' is consistent with the type of the declaration.
9684 if (!InvalidDecl && Mutable) {
9685 unsigned DiagID = 0;
9686 if (T->isReferenceType())
9687 DiagID = diag::err_mutable_reference;
9688 else if (T.isConstQualified())
9689 DiagID = diag::err_mutable_const;
9690
9691 if (DiagID) {
9692 SourceLocation ErrLoc = Loc;
9693 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9694 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9695 Diag(ErrLoc, DiagID);
9696 Mutable = false;
9697 InvalidDecl = true;
9698 }
9699 }
9700
Abramo Bagnaradff19302011-03-08 08:55:46 +00009701 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00009702 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009703 if (InvalidDecl)
9704 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00009705
Douglas Gregor1efa4372009-03-11 18:59:21 +00009706 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9707 Diag(Loc, diag::err_duplicate_member) << II;
9708 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9709 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009710 }
9711
David Blaikiebbafb8a2012-03-11 07:00:24 +00009712 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00009713 if (Record->isUnion()) {
9714 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9715 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9716 if (RDecl->getDefinition()) {
9717 // C++ [class.union]p1: An object of a class with a non-trivial
9718 // constructor, a non-trivial copy constructor, a non-trivial
9719 // destructor, or a non-trivial copy assignment operator
9720 // cannot be a member of a union, nor can an array of such
9721 // objects.
Richard Smithf720df02011-10-19 20:41:51 +00009722 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00009723 NewFD->setInvalidDecl();
9724 }
9725 }
9726
9727 // C++ [class.union]p1: If a union contains a member of reference type,
9728 // the program is ill-formed.
9729 if (EltTy->isReferenceType()) {
9730 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9731 << NewFD->getDeclName() << EltTy;
9732 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00009733 }
9734 }
9735 }
9736
Douglas Gregor1efa4372009-03-11 18:59:21 +00009737 // FIXME: We need to pass in the attributes given an AST
9738 // representation, not a parser representation.
9739 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00009740 // FIXME: What to pass instead of TUScope?
9741 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009742
John McCall31168b02011-06-15 23:02:42 +00009743 // In auto-retain/release, infer strong retension for fields of
9744 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009745 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +00009746 NewFD->setInvalidDecl();
9747
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00009748 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00009749 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00009750
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009751 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00009752 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00009753}
9754
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009755bool Sema::CheckNontrivialField(FieldDecl *FD) {
9756 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009757 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009758
9759 if (FD->isInvalidDecl())
9760 return true;
9761
9762 QualType EltTy = Context.getBaseElementType(FD->getType());
9763 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9764 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9765 if (RDecl->getDefinition()) {
9766 // We check for copy constructors before constructors
9767 // because otherwise we'll never get complaints about
9768 // copy constructors.
9769
9770 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +00009771 // We're required to check for any non-trivial constructors. Since the
9772 // implicit default constructor is suppressed if there are any
9773 // user-declared constructors, we just need to check that there is a
9774 // trivial default constructor and a trivial copy constructor. (We don't
9775 // worry about move constructors here, since this is a C++98 check.)
9776 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009777 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00009778 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009779 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +00009780 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009781 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +00009782 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009783 member = CXXDestructor;
9784
9785 if (member != CXXInvalid) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009786 if (!getLangOpts().CPlusPlus0x &&
9787 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +00009788 // Objective-C++ ARC: it is an error to have a non-trivial field of
9789 // a union. However, system headers in Objective-C programs
9790 // occasionally have Objective-C lifetime objects within unions,
9791 // and rather than cause the program to fail, we make those
9792 // members unavailable.
9793 SourceLocation Loc = FD->getLocation();
9794 if (getSourceManager().isInSystemHeader(Loc)) {
9795 if (!FD->hasAttr<UnavailableAttr>())
9796 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009797 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00009798 return false;
9799 }
9800 }
Richard Smithf720df02011-10-19 20:41:51 +00009801
David Blaikiebbafb8a2012-03-11 07:00:24 +00009802 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
Richard Smithf720df02011-10-19 20:41:51 +00009803 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9804 diag::err_illegal_union_or_anon_struct_member)
9805 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009806 DiagnoseNontrivial(RT, member);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009807 return !getLangOpts().CPlusPlus0x;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009808 }
9809 }
9810 }
9811
9812 return false;
9813}
9814
Douglas Gregora3d3fe92012-08-30 21:47:37 +00009815/// If the given constructor is user-declared, produce a diagnostic explaining
Richard Smith8e1c9322012-02-26 10:50:32 +00009816/// that it makes the class non-trivial.
Douglas Gregora3d3fe92012-08-30 21:47:37 +00009817static bool diagnoseNonTrivialUserDeclaredCtor(Sema &S, QualType QT,
Richard Smith8e1c9322012-02-26 10:50:32 +00009818 CXXConstructorDecl *CD,
9819 Sema::CXXSpecialMember CSM) {
Douglas Gregora3d3fe92012-08-30 21:47:37 +00009820 if (CD->isImplicit())
Richard Smith8e1c9322012-02-26 10:50:32 +00009821 return false;
9822
9823 SourceLocation CtorLoc = CD->getLocation();
9824 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9825 return true;
9826}
9827
Douglas Gregor8a273912009-07-22 18:25:24 +00009828/// DiagnoseNontrivial - Given that a class has a non-trivial
9829/// special member, figure out why.
Richard Smith16488472012-11-16 00:53:38 +00009830/// FIXME: These checks are not correct in C++11 mode. Currently, this is OK
9831/// since we only use this in C++11 for a -Wc++98-compat warning.
Douglas Gregor8a273912009-07-22 18:25:24 +00009832void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9833 QualType QT(T, 0U);
9834 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9835
9836 // Check whether the member was user-declared.
9837 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00009838 case CXXInvalid:
9839 break;
9840
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009841 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00009842 if (RD->hasUserDeclaredConstructor()) {
9843 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Richard Smith8e1c9322012-02-26 10:50:32 +00009844 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
Douglas Gregora3d3fe92012-08-30 21:47:37 +00009845 if (diagnoseNonTrivialUserDeclaredCtor(*this, QT, *CI, member))
Douglas Gregor8a273912009-07-22 18:25:24 +00009846 return;
Douglas Gregor8a273912009-07-22 18:25:24 +00009847
Douglas Gregora3d3fe92012-08-30 21:47:37 +00009848 // No user-delcared constructors; look for constructor templates.
Richard Smith8e1c9322012-02-26 10:50:32 +00009849 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9850 tmpl_iter;
9851 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9852 TI != TE; ++TI) {
9853 CXXConstructorDecl *CD =
9854 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
Douglas Gregora3d3fe92012-08-30 21:47:37 +00009855 if (CD && diagnoseNonTrivialUserDeclaredCtor(*this, QT, CD, member))
Richard Smith8e1c9322012-02-26 10:50:32 +00009856 return;
9857 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009858 }
9859 break;
9860
9861 case CXXCopyConstructor:
9862 if (RD->hasUserDeclaredCopyConstructor()) {
9863 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00009864 RD->getCopyConstructor(0)->getLocation();
9865 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9866 return;
9867 }
9868 break;
9869
9870 case CXXMoveConstructor:
9871 if (RD->hasUserDeclaredMoveConstructor()) {
9872 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009873 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9874 return;
9875 }
9876 break;
9877
9878 case CXXCopyAssignment:
9879 if (RD->hasUserDeclaredCopyAssignment()) {
Benjamin Kramere3895eb2012-07-30 16:41:40 +00009880 SourceLocation AssignLoc =
9881 RD->getCopyAssignmentOperator(0)->getLocation();
9882 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
Douglas Gregor8a273912009-07-22 18:25:24 +00009883 return;
9884 }
9885 break;
9886
Alexis Huntfcaeae42011-05-25 20:50:04 +00009887 case CXXMoveAssignment:
9888 if (RD->hasUserDeclaredMoveAssignment()) {
9889 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9890 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9891 return;
9892 }
9893 break;
9894
Douglas Gregor8a273912009-07-22 18:25:24 +00009895 case CXXDestructor:
9896 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00009897 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009898 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9899 return;
9900 }
9901 break;
9902 }
9903
9904 typedef CXXRecordDecl::base_class_iterator base_iter;
9905
9906 // Virtual bases and members inhibit trivial copying/construction,
9907 // but not trivial destruction.
9908 if (member != CXXDestructor) {
9909 // Check for virtual bases. vbases includes indirect virtual bases,
9910 // so we just iterate through the direct bases.
9911 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9912 if (bi->isVirtual()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009913 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009914 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9915 return;
9916 }
9917
9918 // Check for virtual methods.
9919 typedef CXXRecordDecl::method_iterator meth_iter;
9920 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9921 ++mi) {
9922 if (mi->isVirtual()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009923 SourceLocation MLoc = mi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009924 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9925 return;
9926 }
9927 }
9928 }
Mike Stump11289f42009-09-09 15:08:12 +00009929
Richard Smith16488472012-11-16 00:53:38 +00009930 bool (CXXRecordDecl::*hasNonTrivial)() const;
Douglas Gregor8a273912009-07-22 18:25:24 +00009931 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009932 case CXXDefaultConstructor:
Richard Smith16488472012-11-16 00:53:38 +00009933 hasNonTrivial = &CXXRecordDecl::hasNonTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00009934 case CXXCopyConstructor:
Richard Smith16488472012-11-16 00:53:38 +00009935 hasNonTrivial = &CXXRecordDecl::hasNonTrivialCopyConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00009936 case CXXCopyAssignment:
Richard Smith16488472012-11-16 00:53:38 +00009937 hasNonTrivial = &CXXRecordDecl::hasNonTrivialCopyAssignment; break;
9938 case CXXMoveConstructor:
9939 hasNonTrivial = &CXXRecordDecl::hasNonTrivialMoveConstructor; break;
9940 case CXXMoveAssignment:
9941 hasNonTrivial = &CXXRecordDecl::hasNonTrivialMoveAssignment; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00009942 case CXXDestructor:
Richard Smith16488472012-11-16 00:53:38 +00009943 hasNonTrivial = &CXXRecordDecl::hasNonTrivialDestructor; break;
9944 case CXXInvalid:
David Blaikieaa347f92011-09-23 20:26:49 +00009945 llvm_unreachable("unexpected special member");
Douglas Gregor8a273912009-07-22 18:25:24 +00009946 }
9947
9948 // Check for nontrivial bases (and recurse).
9949 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009950 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00009951 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00009952 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
Richard Smith16488472012-11-16 00:53:38 +00009953 if ((BaseRecTy->*hasNonTrivial)()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009954 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009955 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9956 DiagnoseNontrivial(BaseRT, member);
9957 return;
9958 }
9959 }
Mike Stump11289f42009-09-09 15:08:12 +00009960
Douglas Gregor8a273912009-07-22 18:25:24 +00009961 // Check for nontrivial members (and recurse).
9962 typedef RecordDecl::field_iterator field_iter;
9963 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9964 ++fi) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009965 QualType EltTy = Context.getBaseElementType(fi->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009966 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00009967 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9968
Richard Smith16488472012-11-16 00:53:38 +00009969 if ((EltRD->*hasNonTrivial)()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009970 SourceLocation FLoc = fi->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009971 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9972 DiagnoseNontrivial(EltRT, member);
9973 return;
9974 }
9975 }
John McCall31168b02011-06-15 23:02:42 +00009976
9977 if (EltTy->isObjCLifetimeType()) {
9978 switch (EltTy.getObjCLifetime()) {
9979 case Qualifiers::OCL_None:
9980 case Qualifiers::OCL_ExplicitNone:
9981 break;
9982
9983 case Qualifiers::OCL_Autoreleasing:
9984 case Qualifiers::OCL_Weak:
9985 case Qualifiers::OCL_Strong:
David Blaikie2d7c57e2012-04-30 02:36:29 +00009986 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00009987 << QT << EltTy.getObjCLifetime();
9988 return;
9989 }
9990 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009991 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009992}
9993
Mike Stump11289f42009-09-09 15:08:12 +00009994/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00009995/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00009996static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00009997TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00009998 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +00009999 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000010000 case tok::objc_private: return ObjCIvarDecl::Private;
10001 case tok::objc_public: return ObjCIvarDecl::Public;
10002 case tok::objc_protected: return ObjCIvarDecl::Protected;
10003 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000010004 }
10005}
10006
Mike Stump11289f42009-09-09 15:08:12 +000010007/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000010008/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000010009Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000010010 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000010011 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000010012 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000010013
Fariborz Jahaniande615832008-04-10 23:32:45 +000010014 IdentifierInfo *II = D.getIdentifier();
10015 Expr *BitWidth = (Expr*)BitfieldWidth;
10016 SourceLocation Loc = DeclStart;
10017 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000010018
Fariborz Jahaniande615832008-04-10 23:32:45 +000010019 // FIXME: Unnamed fields can be handled in various different ways, for
10020 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000010021
John McCall8cb7bdf2010-06-04 23:28:52 +000010022 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10023 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000010024
Fariborz Jahaniande615832008-04-10 23:32:45 +000010025 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000010026 // 6.7.2.1p3, 6.7.2.1p4
Richard Smithf4c51d92012-02-04 09:53:13 +000010027 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
10028 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000010029 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000010030 } else {
10031 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000010032
Fariborz Jahaniande615832008-04-10 23:32:45 +000010033 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000010034
Fariborz Jahaniande615832008-04-10 23:32:45 +000010035 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000010036 if (T->isReferenceType()) {
10037 Diag(Loc, diag::err_ivar_reference_type);
10038 D.setInvalidType();
10039 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000010040 // C99 6.7.2.1p8: A member of a structure or union may have any type other
10041 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000010042 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000010043 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000010044 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000010045 }
Mike Stump11289f42009-09-09 15:08:12 +000010046
Ted Kremenek73295fa2008-07-23 18:04:17 +000010047 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000010048 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000010049 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
10050 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000010051 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010052 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000010053 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
10054 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000010055 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000010056 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000010057 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000010058 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000010059 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000010060 EnclosingContext = IMPDecl->getClassInterface();
10061 assert(EnclosingContext && "Implementation has no class interface!");
10062 }
10063 else
10064 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010065 } else {
10066 if (ObjCCategoryDecl *CDecl =
10067 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000010068 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010069 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000010070 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010071 }
10072 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000010073 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010074 }
Mike Stump11289f42009-09-09 15:08:12 +000010075
Ted Kremenek73295fa2008-07-23 18:04:17 +000010076 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000010077 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
10078 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000010079 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000010080
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010081 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010082 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000010083 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000010084 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010085 && !isa<TagDecl>(PrevDecl)) {
10086 Diag(Loc, diag::err_duplicate_member) << II;
10087 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10088 NewID->setInvalidDecl();
10089 }
10090 }
10091
Ted Kremenek73295fa2008-07-23 18:04:17 +000010092 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000010093 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000010094
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000010095 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000010096 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000010097
John McCall31168b02011-06-15 23:02:42 +000010098 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010099 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000010100 NewID->setInvalidDecl();
10101
Douglas Gregor3baa6702011-09-12 16:11:24 +000010102 if (D.getDeclSpec().isModulePrivateSpecified())
10103 NewID->setModulePrivate();
10104
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010105 if (II) {
10106 // FIXME: When interfaces are DeclContexts, we'll need to add
10107 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000010108 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010109 IdResolver.AddDecl(NewID);
10110 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000010111
John McCall5fb5df92012-06-20 06:18:46 +000010112 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000010113 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000010114 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000010115
John McCall48871652010-08-21 09:40:31 +000010116 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000010117}
10118
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010119/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
10120/// class and class extensions. For every class @interface and class
10121/// extension @interface, if the last ivar is a bitfield of any type,
10122/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010123void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010124 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000010125 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010126 return;
10127
10128 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
10129 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
10130
Richard Smithcaf33902011-10-10 18:28:20 +000010131 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010132 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010133 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010134 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010135 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010136 if (!CD->IsClassExtension())
10137 return;
10138 }
10139 // No need to add this to end of @implementation.
10140 else
10141 return;
10142 }
10143 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000010144 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
10145 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010146
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010147 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000010148 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010149 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000010150 Context.getTrivialTypeSourceInfo(Context.CharTy,
10151 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000010152 ObjCIvarDecl::Private, BW,
10153 true);
10154 AllIvarDecls.push_back(Ivar);
10155}
10156
Fariborz Jahanian343f7092007-09-29 00:54:24 +000010157void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +000010158 SourceLocation RecLoc, Decl *EnclosingDecl,
David Blaikie751c5582011-09-22 02:58:26 +000010159 llvm::ArrayRef<Decl *> Fields,
Daniel Dunbar15619c72008-10-03 02:03:53 +000010160 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +000010161 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000010162 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000010163
Eric Christopher7457aaf2012-07-19 22:22:51 +000010164 // If this is an Objective-C @implementation or category and we have
10165 // new fields here we should reset the layout of the interface since
10166 // it will now change.
10167 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
10168 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
10169 switch (DC->getKind()) {
10170 default: break;
10171 case Decl::ObjCCategory:
10172 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
10173 break;
10174 case Decl::ObjCImplementation:
10175 Context.
10176 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
10177 break;
10178 }
10179 }
10180
Eli Friedmana7679412012-02-07 05:00:47 +000010181 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
10182
10183 // Start counting up the number of named members; make sure to include
10184 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000010185 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000010186 if (Record) {
10187 for (RecordDecl::decl_iterator i = Record->decls_begin(),
10188 e = Record->decls_end(); i != e; i++) {
10189 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
10190 if (IFD->getDeclName())
10191 ++NumNamedMembers;
10192 }
10193 }
10194
10195 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010196 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000010197
John McCall31168b02011-06-15 23:02:42 +000010198 bool ARCErrReported = false;
David Blaikie751c5582011-09-22 02:58:26 +000010199 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
10200 i != end; ++i) {
10201 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000010202
Chris Lattner720a0542007-01-25 00:44:24 +000010203 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000010204 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000010205
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010206 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000010207 // Remember all fields written by the user.
10208 RecFields.push_back(FD);
10209 }
Mike Stump11289f42009-09-09 15:08:12 +000010210
Chris Lattner73bf7b42009-03-05 22:45:59 +000010211 // If the field is already invalid for some reason, don't emit more
10212 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000010213 if (FD->isInvalidDecl()) {
10214 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000010215 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000010216 }
Mike Stump11289f42009-09-09 15:08:12 +000010217
Douglas Gregorac1fb652009-03-24 19:52:54 +000010218 // C99 6.7.2.1p2:
10219 // A structure or union shall not contain a member with
10220 // incomplete or function type (hence, a structure shall not
10221 // contain an instance of itself, but may contain a pointer to
10222 // an instance of itself), except that the last member of a
10223 // structure with more than one named member may have incomplete
10224 // array type; such a structure (and any union containing,
10225 // possibly recursively, a member that is such a structure)
10226 // shall not be a member of a structure or an element of an
10227 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000010228 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000010229 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000010230 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010231 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000010232 FD->setInvalidDecl();
10233 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000010234 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000010235 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000010236 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010237 ((getLangOpts().MicrosoftExt ||
10238 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000010239 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000010240 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000010241 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000010242 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000010243 // as the sole element of a struct/class.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010244 if (getLangOpts().MicrosoftExt) {
Francois Pichetf657b632010-09-15 00:14:08 +000010245 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000010246 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +000010247 << FD->getDeclName();
David Blaikie751c5582011-09-22 02:58:26 +000010248 else if (Fields.size() == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000010249 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +000010250 << FD->getDeclName() << Record->getTagKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010251 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000010252 if (Record->isUnion())
10253 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10254 << FD->getDeclName();
David Blaikie751c5582011-09-22 02:58:26 +000010255 else if (Fields.size() == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000010256 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
10257 << FD->getDeclName() << Record->getTagKind();
David Chisnall07518f22012-03-16 12:15:37 +000010258 } else if (!getLangOpts().C99) {
10259 if (Record->isUnion())
10260 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10261 << FD->getDeclName();
10262 else
10263 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
10264 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000010265 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010266 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010267 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000010268 FD->setInvalidDecl();
10269 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +000010270 continue;
10271 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010272 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +000010273 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010274 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000010275 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010276 FD->setInvalidDecl();
10277 EnclosingDecl->setInvalidDecl();
10278 continue;
10279 }
Chris Lattner720a0542007-01-25 00:44:24 +000010280 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000010281 if (Record)
10282 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000010283 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000010284 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000010285 diag::err_field_incomplete)) {
10286 // Incomplete type
10287 FD->setInvalidDecl();
10288 EnclosingDecl->setInvalidDecl();
10289 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010290 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000010291 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
10292 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010293 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000010294 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000010295 } else {
10296 // If this is a struct/class and this is not the last element, reject
10297 // it. Note that GCC supports variable sized arrays in the middle of
10298 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000010299 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000010300 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000010301 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000010302 else {
10303 // We support flexible arrays at the end of structs in
10304 // other structs as an extension.
10305 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
10306 << FD->getDeclName();
10307 if (Record)
10308 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000010309 }
Chris Lattner720a0542007-01-25 00:44:24 +000010310 }
10311 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000010312 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
10313 RequireNonAbstractType(FD->getLocation(), FD->getType(),
10314 diag::err_abstract_type_in_decl,
10315 AbstractIvarType)) {
10316 // Ivars can not have abstract class types
10317 FD->setInvalidDecl();
10318 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000010319 if (Record && FDTTy->getDecl()->hasObjectMember())
10320 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000010321 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000010322 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000010323 Diag(FD->getLocation(), diag::err_statically_allocated_object)
10324 << FixItHint::CreateInsertion(FD->getLocation(), "*");
10325 QualType T = Context.getObjCObjectPointerType(FD->getType());
10326 FD->setType(T);
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000010327 } else if (!getLangOpts().CPlusPlus) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010328 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
John McCall31168b02011-06-15 23:02:42 +000010329 // It's an error in ARC if a field has lifetime.
10330 // We don't want to report this in a system header, though,
10331 // so we just make the field unavailable.
10332 // FIXME: that's really not sufficient; we need to make the type
10333 // itself invalid to, say, initialize or copy.
10334 QualType T = FD->getType();
10335 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
10336 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
10337 SourceLocation loc = FD->getLocation();
10338 if (getSourceManager().isInSystemHeader(loc)) {
10339 if (!FD->hasAttr<UnavailableAttr>()) {
10340 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000010341 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000010342 }
10343 } else {
Fariborz Jahanianb989e6e2011-12-12 23:17:04 +000010344 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
10345 << T->isBlockPointerType();
John McCall31168b02011-06-15 23:02:42 +000010346 }
10347 ARCErrReported = true;
10348 }
10349 }
David Blaikiebbafb8a2012-03-11 07:00:24 +000010350 else if (getLangOpts().ObjC1 &&
10351 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000010352 Record && !Record->hasObjectMember()) {
10353 if (FD->getType()->isObjCObjectPointerType() ||
10354 FD->getType().isObjCGCStrong())
10355 Record->setHasObjectMember(true);
10356 else if (Context.getAsArrayType(FD->getType())) {
10357 QualType BaseType = Context.getBaseElementType(FD->getType());
10358 if (BaseType->isRecordType() &&
10359 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
10360 Record->setHasObjectMember(true);
10361 else if (BaseType->isObjCObjectPointerType() ||
10362 BaseType.isObjCGCStrong())
10363 Record->setHasObjectMember(true);
10364 }
10365 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000010366 }
Chris Lattner82625602007-01-24 02:26:21 +000010367 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010368 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000010369 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000010370 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010371
Chris Lattner82625602007-01-24 02:26:21 +000010372 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000010373 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000010374 bool Completed = false;
10375 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
10376 if (!CXXRecord->isInvalidDecl()) {
10377 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010378 for (CXXRecordDecl::conversion_iterator
10379 I = CXXRecord->conversion_begin(),
10380 E = CXXRecord->conversion_end(); I != E; ++I)
10381 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000010382
10383 if (!CXXRecord->isDependentType()) {
Sebastian Redl623ea822011-05-19 05:13:44 +000010384 // Adjust user-defined destructor exception spec.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010385 if (getLangOpts().CPlusPlus0x &&
Sebastian Redl623ea822011-05-19 05:13:44 +000010386 CXXRecord->hasUserDeclaredDestructor())
10387 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10388
Douglas Gregor8fb95122010-09-29 00:15:42 +000010389 // Add any implicitly-declared members to this class.
10390 AddImplicitlyDeclaredMembersToClass(CXXRecord);
10391
10392 // If we have virtual base classes, we may end up finding multiple
10393 // final overriders for a given virtual function. Check for this
10394 // problem now.
10395 if (CXXRecord->getNumVBases()) {
10396 CXXFinalOverriderMap FinalOverriders;
10397 CXXRecord->getFinalOverriders(FinalOverriders);
10398
10399 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10400 MEnd = FinalOverriders.end();
10401 M != MEnd; ++M) {
10402 for (OverridingMethods::iterator SO = M->second.begin(),
10403 SOEnd = M->second.end();
10404 SO != SOEnd; ++SO) {
10405 assert(SO->second.size() > 0 &&
10406 "Virtual function without overridding functions?");
10407 if (SO->second.size() == 1)
10408 continue;
10409
10410 // C++ [class.virtual]p2:
10411 // In a derived class, if a virtual member function of a base
10412 // class subobject has more than one final overrider the
10413 // program is ill-formed.
10414 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000010415 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000010416 Diag(M->first->getLocation(),
10417 diag::note_overridden_virtual_function);
10418 for (OverridingMethods::overriding_iterator
10419 OM = SO->second.begin(),
10420 OMEnd = SO->second.end();
10421 OM != OMEnd; ++OM)
10422 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000010423 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000010424
10425 Record->setInvalidDecl();
10426 }
10427 }
10428 CXXRecord->completeDefinition(&FinalOverriders);
10429 Completed = true;
10430 }
10431 }
10432 }
10433 }
10434
10435 if (!Completed)
10436 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000010437
Chris Lattner622c1932008-02-06 00:51:33 +000010438 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000010439 ObjCIvarDecl **ClsFields =
10440 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000010441 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000010442 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000010443 // Add ivar's to class's DeclContext.
10444 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10445 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010446 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000010447 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000010448 // Must enforce the rule that ivars in the base classes may not be
10449 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000010450 if (ID->getSuperClass())
10451 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000010452 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000010453 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000010454 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000010455 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
10456 // Ivar declared in @implementation never belongs to the implementation.
10457 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000010458 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000010459 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000010460 IMPDecl->setIvarLBraceLoc(LBrac);
10461 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000010462 } else if (ObjCCategoryDecl *CDecl =
10463 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010464 // case of ivars in class extension; all other cases have been
10465 // reported as errors elsewhere.
10466 // FIXME. Class extension does not have a LocEnd field.
10467 // CDecl->setLocEnd(RBrac);
10468 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000010469 // Diagnose redeclaration of private ivars.
10470 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010471 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000010472 if (IDecl) {
10473 if (const ObjCIvarDecl *ClsIvar =
10474 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10475 Diag(ClsFields[i]->getLocation(),
10476 diag::err_duplicate_ivar_declaration);
10477 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
10478 continue;
10479 }
10480 for (const ObjCCategoryDecl *ClsExtDecl =
10481 IDecl->getFirstClassExtension();
10482 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
10483 if (const ObjCIvarDecl *ClsExtIvar =
10484 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10485 Diag(ClsFields[i]->getLocation(),
10486 diag::err_duplicate_ivar_declaration);
10487 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
10488 continue;
10489 }
10490 }
10491 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010492 ClsFields[i]->setLexicalDeclContext(CDecl);
10493 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000010494 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000010495 CDecl->setIvarLBraceLoc(LBrac);
10496 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000010497 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000010498 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000010499
10500 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000010501 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000010502}
10503
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010504/// \brief Determine whether the given integral value is representable within
10505/// the given type T.
10506static bool isRepresentableIntegerValue(ASTContext &Context,
10507 llvm::APSInt &Value,
10508 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000010509 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000010510 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010511
Douglas Gregor0bf31402010-10-08 23:50:27 +000010512 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010513 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000010514 --BitWidth;
10515 return Value.getActiveBits() <= BitWidth;
10516 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010517 return Value.getMinSignedBits() <= BitWidth;
10518}
10519
10520// \brief Given an integral type, return the next larger integral type
10521// (or a NULL type of no such type exists).
10522static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
10523 // FIXME: Int128/UInt128 support, which also needs to be introduced into
10524 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000010525 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010526 const unsigned NumTypes = 4;
10527 QualType SignedIntegralTypes[NumTypes] = {
10528 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
10529 };
10530 QualType UnsignedIntegralTypes[NumTypes] = {
10531 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
10532 Context.UnsignedLongLongTy
10533 };
10534
10535 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010536 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
10537 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010538 for (unsigned I = 0; I != NumTypes; ++I)
10539 if (Context.getTypeSize(Types[I]) > BitWidth)
10540 return Types[I];
10541
10542 return QualType();
10543}
10544
Douglas Gregor954f6b272009-03-17 19:05:46 +000010545EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
10546 EnumConstantDecl *LastEnumConst,
10547 SourceLocation IdLoc,
10548 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000010549 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010550 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010551 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000010552 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010553
10554 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
10555 Val = 0;
10556
Eli Friedman7c6515a2011-12-06 00:10:34 +000010557 if (Val)
10558 Val = DefaultLvalueConversion(Val).take();
10559
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010560 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000010561 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010562 EltTy = Context.DependentTy;
10563 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010564 SourceLocation ExpLoc;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010565 if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
10566 !getLangOpts().MicrosoftMode) {
Richard Smithf8379a02012-01-18 23:55:52 +000010567 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
10568 // constant-expression in the enumerator-definition shall be a converted
10569 // constant expression of the underlying type.
10570 EltTy = Enum->getIntegerType();
10571 ExprResult Converted =
10572 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
10573 CCEK_Enumerator);
10574 if (Converted.isInvalid())
10575 Val = 0;
10576 else
10577 Val = Converted.take();
10578 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000010579 !(Val = VerifyIntegerConstantExpression(Val,
10580 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000010581 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000010582 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010583 if (Enum->isFixed()) {
10584 EltTy = Enum->getIntegerType();
10585
Richard Smithf8379a02012-01-18 23:55:52 +000010586 // In Obj-C and Microsoft mode, require the enumeration value to be
10587 // representable in the underlying type of the enumeration. In C++11,
10588 // we perform a non-narrowing conversion as part of converted constant
10589 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000010590 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010591 if (getLangOpts().MicrosoftMode) {
Francois Picheta3108062010-10-18 15:01:13 +000010592 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000010593 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000010594 } else
10595 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000010596 } else
John Wiegley01296292011-04-08 18:41:53 +000010597 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010598 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000010599 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000010600 // If the underlying type is not fixed, the type of each enumerator
10601 // is the type of its initializing value:
10602 // - If an initializer is specified for an enumerator, the
10603 // initializing value has the same type as the expression.
10604 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000010605 } else {
10606 // C99 6.7.2.2p2:
10607 // The expression that defines the value of an enumeration constant
10608 // shall be an integer constant expression that has a value
10609 // representable as an int.
10610
10611 // Complain if the value is not representable in an int.
10612 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10613 Diag(IdLoc, diag::ext_enum_value_not_int)
10614 << EnumVal.toString(10) << Val->getSourceRange()
10615 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10616 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10617 // Force the type of the expression to 'int'.
10618 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10619 }
10620 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010621 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010622 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000010623 }
10624 }
Mike Stump11289f42009-09-09 15:08:12 +000010625
Douglas Gregor954f6b272009-03-17 19:05:46 +000010626 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000010627 if (Enum->isDependentType())
10628 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010629 else if (!LastEnumConst) {
10630 // C++0x [dcl.enum]p5:
10631 // If the underlying type is not fixed, the type of each enumerator
10632 // is the type of its initializing value:
10633 // - If no initializer is specified for the first enumerator, the
10634 // initializing value has an unspecified integral type.
10635 //
10636 // GCC uses 'int' for its unspecified integral type, as does
10637 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000010638 if (Enum->isFixed()) {
10639 EltTy = Enum->getIntegerType();
10640 }
10641 else {
10642 EltTy = Context.IntTy;
10643 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010644 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000010645 // Assign the last value + 1.
10646 EnumVal = LastEnumConst->getInitVal();
10647 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010648 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000010649
10650 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010651 if (EnumVal < LastEnumConst->getInitVal()) {
10652 // C++0x [dcl.enum]p5:
10653 // If the underlying type is not fixed, the type of each enumerator
10654 // is the type of its initializing value:
10655 //
10656 // - Otherwise the type of the initializing value is the same as
10657 // the type of the initializing value of the preceding enumerator
10658 // unless the incremented value is not representable in that type,
10659 // in which case the type is an unspecified integral type
10660 // sufficient to contain the incremented value. If no such type
10661 // exists, the program is ill-formed.
10662 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010663 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010664 // There is no integral type larger enough to represent this
10665 // value. Complain, then allow the value to wrap around.
10666 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000010667 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010668 ++EnumVal;
10669 if (Enum->isFixed())
10670 // When the underlying type is fixed, this is ill-formed.
10671 Diag(IdLoc, diag::err_enumerator_wrapped)
10672 << EnumVal.toString(10)
10673 << EltTy;
10674 else
10675 Diag(IdLoc, diag::warn_enumerator_too_large)
10676 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010677 } else {
10678 EltTy = T;
10679 }
10680
10681 // Retrieve the last enumerator's value, extent that type to the
10682 // type that is supposed to be large enough to represent the incremented
10683 // value, then increment.
10684 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010685 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000010686 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010687 ++EnumVal;
10688
10689 // If we're not in C++, diagnose the overflow of enumerator values,
10690 // which in C99 means that the enumerator value is not representable in
10691 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10692 // permits enumerator values that are representable in some larger
10693 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010694 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010695 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010696 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010697 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10698 // Enforce C99 6.7.2.2p2 even when we compute the next value.
10699 Diag(IdLoc, diag::ext_enum_value_not_int)
10700 << EnumVal.toString(10) << 1;
10701 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000010702 }
10703 }
Mike Stump11289f42009-09-09 15:08:12 +000010704
Douglas Gregordc70c3a2010-03-02 17:53:14 +000010705 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010706 // Make the enumerator value match the signedness and size of the
10707 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000010708 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010709 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010710 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010711
Douglas Gregor954f6b272009-03-17 19:05:46 +000010712 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000010713 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000010714}
10715
10716
John McCall811a0f52010-10-22 23:36:17 +000010717Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10718 SourceLocation IdLoc, IdentifierInfo *Id,
10719 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000010720 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000010721 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000010722 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000010723 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000010724
Chris Lattner1a76a3c2007-08-26 06:24:45 +000010725 // The scope passed in may not be a decl scope. Zip up the scope tree until
10726 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000010727 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000010728
Chris Lattner8116d1b2007-01-25 22:38:29 +000010729 // Verify that there isn't already something declared with this name in this
10730 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010731 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000010732 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000010733 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010734 // Maybe we will complain about the shadowed template parameter.
10735 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10736 // Just pretend that we didn't see the previous declaration.
10737 PrevDecl = 0;
10738 }
10739
10740 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000010741 // When in C++, we may get a TagDecl with the same name; in this case the
10742 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010743 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000010744 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000010745 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000010746 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010747 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000010748 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010749 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000010750 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000010751 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000010752 }
10753 }
Chris Lattner4ef40012007-06-11 01:28:17 +000010754
Aaron Ballman24a10472012-07-19 03:12:23 +000010755 // C++ [class.mem]p15:
10756 // If T is the name of a class, then each of the following shall have a name
10757 // different from T:
10758 // - every enumerator of every member of class T that is an unscoped
10759 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000010760 if (CXXRecordDecl *Record
10761 = dyn_cast<CXXRecordDecl>(
10762 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000010763 if (!TheEnumDecl->isScoped() &&
10764 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000010765 Diag(IdLoc, diag::err_member_name_of_class) << Id;
10766
John McCall811a0f52010-10-22 23:36:17 +000010767 EnumConstantDecl *New =
10768 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000010769
John McCall553c0792010-01-23 00:46:32 +000010770 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000010771 // Process attributes.
10772 if (Attr) ProcessDeclAttributeList(S, New, Attr);
10773
10774 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000010775 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000010776 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000010777 }
Douglas Gregor2f521192008-12-17 02:04:30 +000010778
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000010779 ActOnDocumentableDecl(New);
10780
John McCall48871652010-08-21 09:40:31 +000010781 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000010782}
10783
Mike Stump6814d1c2009-05-16 07:06:02 +000010784void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000010785 SourceLocation RBraceLoc, Decl *EnumDeclX,
10786 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010787 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000010788 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000010789 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010790
10791 if (Attr)
10792 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000010793
Eli Friedmand0e60972009-12-11 01:34:50 +000010794 if (Enum->isDependentType()) {
10795 for (unsigned i = 0; i != NumElements; ++i) {
10796 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000010797 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000010798 if (!ECD) continue;
10799
10800 ECD->setType(EnumType);
10801 }
10802
John McCall9aa35be2010-05-06 08:49:23 +000010803 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000010804 return;
10805 }
10806
Chris Lattner67933c02007-08-28 05:10:31 +000010807 // TODO: If the result value doesn't fit in an int, it must be a long or long
10808 // long value. ISO C does not support this, but GCC does as an extension,
10809 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000010810 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10811 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10812 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010813
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010814 // Verify that all the values are okay, compute the size of the values, and
10815 // reverse the list.
10816 unsigned NumNegativeBits = 0;
10817 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000010818
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010819 // Keep track of whether all elements have type int.
10820 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000010821
Chris Lattnerc1915e22007-01-25 07:29:02 +000010822 for (unsigned i = 0; i != NumElements; ++i) {
10823 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000010824 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000010825 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000010826
Chris Lattnerbf478cb2007-08-28 05:27:00 +000010827 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000010828
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010829 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000010830 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000010831 NumPositiveBits = std::max(NumPositiveBits,
10832 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010833 else
Chris Lattner49f980c2008-01-14 21:47:29 +000010834 NumNegativeBits = std::max(NumNegativeBits,
10835 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000010836
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010837 // Keep track of whether every enum element has type int (very commmon).
10838 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000010839 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000010840 }
Mike Stump11289f42009-09-09 15:08:12 +000010841
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010842 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010843 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010844 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010845
John McCall56774992009-12-09 09:09:27 +000010846 // C++0x N3000 [conv.prom]p3:
10847 // An rvalue of an unscoped enumeration type whose underlying
10848 // type is not fixed can be converted to an rvalue of the first
10849 // of the following types that can represent all the values of
10850 // the enumeration: int, unsigned int, long int, unsigned long
10851 // int, long long int, or unsigned long long int.
10852 // C99 6.4.4.3p2:
10853 // An identifier declared as an enumeration constant has type int.
10854 // The C99 rule is modified by a gcc extension
10855 QualType BestPromotionType;
10856
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010857 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000010858 // -fshort-enums is the equivalent to specifying the packed attribute on all
10859 // enum definitions.
10860 if (LangOpts.ShortEnums)
10861 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010862
Douglas Gregor0bf31402010-10-08 23:50:27 +000010863 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000010864 BestType = Enum->getIntegerType();
10865 if (BestType->isPromotableIntegerType())
10866 BestPromotionType = Context.getPromotedIntegerType(BestType);
10867 else
10868 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000010869 // We don't need to set BestWidth, because BestType is going to be the type
10870 // of the enumerators, but we do anyway because otherwise some compilers
10871 // warn that it might be used uninitialized.
10872 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010873 }
10874 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000010875 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010876 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010877 // If it's packed, check also if it fits a char or a short.
10878 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000010879 BestType = Context.SignedCharTy;
10880 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000010881 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010882 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000010883 BestType = Context.ShortTy;
10884 BestWidth = ShortWidth;
10885 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010886 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010887 BestWidth = IntWidth;
10888 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010889 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010890
John McCall56774992009-12-09 09:09:27 +000010891 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010892 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000010893 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010894 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010895
Chris Lattner3a370bf2007-08-29 17:31:48 +000010896 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010897 Diag(Enum->getLocation(), diag::warn_enum_too_large);
10898 BestType = Context.LongLongTy;
10899 }
10900 }
John McCall56774992009-12-09 09:09:27 +000010901 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010902 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000010903 // If there is no negative value, figure out the smallest type that fits
10904 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010905 // If it's packed, check also if it fits a char or a short.
10906 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000010907 BestType = Context.UnsignedCharTy;
10908 BestPromotionType = Context.IntTy;
10909 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010910 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000010911 BestType = Context.UnsignedShortTy;
10912 BestPromotionType = Context.IntTy;
10913 BestWidth = ShortWidth;
10914 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010915 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010916 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000010917 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010918 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010919 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010920 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000010921 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010922 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000010923 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010924 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010925 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000010926 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010927 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010928 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010929 "How could an initializer get larger than ULL?");
10930 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000010931 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010932 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010933 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010934 }
10935 }
Mike Stump11289f42009-09-09 15:08:12 +000010936
Chris Lattner3a370bf2007-08-29 17:31:48 +000010937 // Loop over all of the enumerator constants, changing their types to match
10938 // the type of the enum if needed.
10939 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +000010940 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010941 if (!ECD) continue; // Already issued a diagnostic.
10942
10943 // Standard C says the enumerators have int type, but we allow, as an
10944 // extension, the enumerators to be larger than int size. If each
10945 // enumerator value fits in an int, type it as an int, otherwise type it the
10946 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
10947 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000010948
10949 // Determine whether the value fits into an int.
10950 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010951
10952 // If it fits into an integer type, force it. Otherwise force it to match
10953 // the enum decl type.
10954 QualType NewTy;
10955 unsigned NewWidth;
10956 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010957 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000010958 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010959 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000010960 NewTy = Context.IntTy;
10961 NewWidth = IntWidth;
10962 NewSign = true;
10963 } else if (ECD->getType() == BestType) {
10964 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000010965 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000010966 // C++ [dcl.enum]p4: Following the closing brace of an
10967 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000010968 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000010969 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010970 continue;
10971 } else {
10972 NewTy = BestType;
10973 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010974 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010975 }
10976
10977 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010978 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010979 InitVal.setIsSigned(NewSign);
10980 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000010981
Chris Lattner3a370bf2007-08-29 17:31:48 +000010982 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000010983 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000010984 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000010985 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000010986 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000010987 ECD->getInitExpr(),
10988 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000010989 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000010990 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000010991 // C++ [dcl.enum]p4: Following the closing brace of an
10992 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000010993 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000010994 ECD->setType(EnumType);
10995 else
10996 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010997 }
Mike Stump11289f42009-09-09 15:08:12 +000010998
John McCall9aa35be2010-05-06 08:49:23 +000010999 Enum->completeDefinition(BestType, BestPromotionType,
11000 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000011001
11002 // If we're declaring a function, ensure this decl isn't forgotten about -
11003 // it needs to go into the function scope.
11004 if (InFunctionDeclarator)
11005 DeclsInPrototypeScope.push_back(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000011006}
Chris Lattner1300fb92007-01-23 23:42:53 +000011007
Abramo Bagnara348823a2011-03-03 14:20:18 +000011008Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
11009 SourceLocation StartLoc,
11010 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000011011 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000011012
Douglas Gregor278f52e2009-05-30 00:08:05 +000011013 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000011014 AsmString, StartLoc,
11015 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011016 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000011017 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000011018}
Eli Friedman5ed51982009-06-05 02:44:36 +000011019
Douglas Gregor22d09742012-01-03 18:04:46 +000011020DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
11021 SourceLocation ImportLoc,
11022 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000011023 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000011024 Module::AllVisible,
11025 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000011026 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000011027 return true;
11028
Douglas Gregorba345522011-12-02 23:23:56 +000011029 llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
11030 Module *ModCheck = Mod;
11031 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
11032 // If we've run out of module parents, just drop the remaining identifiers.
11033 // We need the length to be consistent.
11034 if (!ModCheck)
11035 break;
11036 ModCheck = ModCheck->Parent;
11037
11038 IdentifierLocs.push_back(Path[I].second);
11039 }
11040
11041 ImportDecl *Import = ImportDecl::Create(Context,
11042 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000011043 AtLoc.isValid()? AtLoc : ImportLoc,
11044 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000011045 Context.getTranslationUnitDecl()->addDecl(Import);
11046 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000011047}
11048
David Chisnall0867d9c2012-02-18 16:12:34 +000011049void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
11050 IdentifierInfo* AliasName,
11051 SourceLocation PragmaLoc,
11052 SourceLocation NameLoc,
11053 SourceLocation AliasNameLoc) {
11054 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
11055 LookupOrdinaryName);
11056 AsmLabelAttr *Attr =
11057 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall0867d9c2012-02-18 16:12:34 +000011058
11059 if (PrevDecl)
11060 PrevDecl->addAttr(Attr);
11061 else
11062 (void)ExtnameUndeclaredIdentifiers.insert(
11063 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
11064}
11065
Eli Friedman5ed51982009-06-05 02:44:36 +000011066void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
11067 SourceLocation PragmaLoc,
11068 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011069 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000011070
Eli Friedman5ed51982009-06-05 02:44:36 +000011071 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +000011072 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +000011073 } else {
11074 (void)WeakUndeclaredIdentifiers.insert(
11075 std::pair<IdentifierInfo*,WeakInfo>
11076 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000011077 }
Eli Friedman5ed51982009-06-05 02:44:36 +000011078}
11079
11080void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
11081 IdentifierInfo* AliasName,
11082 SourceLocation PragmaLoc,
11083 SourceLocation NameLoc,
11084 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011085 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
11086 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000011087 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000011088
Eli Friedman5ed51982009-06-05 02:44:36 +000011089 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000011090 if (!PrevDecl->hasAttr<AliasAttr>())
11091 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000011092 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000011093 } else {
11094 (void)WeakUndeclaredIdentifiers.insert(
11095 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000011096 }
Eli Friedman5ed51982009-06-05 02:44:36 +000011097}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011098
11099Decl *Sema::getObjCDeclContext() const {
11100 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
11101}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000011102
11103AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000011104 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000011105 return D->getAvailability();
11106}