blob: cbf2368f7123b0008ab795afd3375d9dafba7ba8 [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,
353/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
354/// where the user forgot to specify the tag.
355DeclSpec::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;
364 case TTK_Union: return DeclSpec::TST_union;
365 case TTK_Class: return DeclSpec::TST_class;
366 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000367 }
368 }
Mike Stump11289f42009-09-09 15:08:12 +0000369
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000370 return DeclSpec::TST_unspecified;
371}
372
Francois Pichet48c946e2011-04-13 02:38:49 +0000373/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
374/// if a CXXScopeSpec's type is equal to the type of one of the base classes
375/// then downgrade the missing typename error to a warning.
376/// This is needed for MSVC compatibility; Example:
377/// @code
378/// template<class T> class A {
379/// public:
380/// typedef int TYPE;
381/// };
382/// template<class T> class B : public A<T> {
383/// public:
384/// A<T>::TYPE a; // no typename required because A<T> is a base class.
385/// };
386/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000387bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000388 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000389 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000390
391 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
392 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
393 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
394 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
395 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000396 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000397 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000398 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000399}
400
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000401bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000402 SourceLocation IILoc,
403 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000404 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000405 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000406 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000407 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000408
Douglas Gregor2d435302009-12-30 17:04:44 +0000409 // There may have been a typo in the name of the type. Look up typo
410 // results, in case we have something that we can suggest.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000411 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000412 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000413 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000414 Validator)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000415 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
416 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000417
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000418 if (Corrected.isKeyword()) {
419 // We corrected to a keyword.
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000420 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
421 if (!isSimpleTypeSpecifier(NewII->getTokenID()))
422 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000423 Diag(IILoc, diag::err_unknown_typename_suggest)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000424 << II << CorrectedQuotedStr
425 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
426 II = NewII;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000427 } else {
428 NamedDecl *Result = Corrected.getCorrectionDecl();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000429 // We found a similarly-named type or interface; suggest that.
430 if (!SS || !SS->isSet())
431 Diag(IILoc, diag::err_unknown_typename_suggest)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000432 << II << CorrectedQuotedStr
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000433 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
434 else if (DeclContext *DC = computeDeclContext(*SS, false))
435 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000436 << II << DC << CorrectedQuotedStr << SS->getRange()
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000437 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
438 else
439 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000440
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000441 Diag(Result->getLocation(), diag::note_previous_decl)
442 << CorrectedQuotedStr;
443
444 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
445 false, false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000446 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000447 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000448 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000449 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000450 }
451
David Blaikiebbafb8a2012-03-11 07:00:24 +0000452 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000453 // See if II is a class template that the user forgot to pass arguments to.
454 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000455 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000456 CXXScopeSpec EmptySS;
457 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000458 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000459 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000460 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000461 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000462 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
463 Diag(IILoc, diag::err_template_missing_args) << TplName;
464 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
465 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
466 << TplDecl->getTemplateParameters()->getSourceRange();
467 }
468 return true;
469 }
470 }
471
Douglas Gregor15e56022009-10-13 23:27:22 +0000472 // FIXME: Should we move the logic that tries to recover from a missing tag
473 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
474
Douglas Gregor2d435302009-12-30 17:04:44 +0000475 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000476 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000477 else if (DeclContext *DC = computeDeclContext(*SS, false))
478 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000479 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000480 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000481 unsigned DiagID = diag::err_typename_missing;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000482 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000483 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000484
485 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000486 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000487 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000488 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000489 SuggestedType = ActOnTypenameType(S, SourceLocation(),
490 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000491 } else {
492 assert(SS && SS->isInvalid() &&
493 "Invalid scope specifier has already been diagnosed");
494 }
495
496 return true;
497}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000498
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000499/// \brief Determine whether the given result set contains either a type name
500/// or
501static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000502 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000503 NextToken.is(tok::less);
504
505 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
506 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
507 return true;
508
509 if (CheckTemplate && isa<TemplateDecl>(*I))
510 return true;
511 }
512
513 return false;
514}
515
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000516static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
517 Scope *S, CXXScopeSpec &SS,
518 IdentifierInfo *&Name,
519 SourceLocation NameLoc) {
520 Result.clear(Sema::LookupTagName);
521 SemaRef.LookupParsedName(Result, S, &SS);
522 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
523 const char *TagName = 0;
524 const char *FixItTagName = 0;
525 switch (Tag->getTagKind()) {
526 case TTK_Class:
527 TagName = "class";
528 FixItTagName = "class ";
529 break;
530
531 case TTK_Enum:
532 TagName = "enum";
533 FixItTagName = "enum ";
534 break;
535
536 case TTK_Struct:
537 TagName = "struct";
538 FixItTagName = "struct ";
539 break;
540
541 case TTK_Union:
542 TagName = "union";
543 FixItTagName = "union ";
544 break;
545 }
546
547 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
548 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
549 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
550
551 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName);
552 if (SemaRef.LookupParsedName(R, S, &SS)) {
553 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
554 I != IEnd; ++I)
555 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
556 << Name << TagName;
557 }
558 return true;
559 }
560
561 Result.clear(Sema::LookupOrdinaryName);
562 return false;
563}
564
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000565Sema::NameClassification Sema::ClassifyName(Scope *S,
566 CXXScopeSpec &SS,
567 IdentifierInfo *&Name,
568 SourceLocation NameLoc,
569 const Token &NextToken) {
570 DeclarationNameInfo NameInfo(Name, NameLoc);
571 ObjCMethodDecl *CurMethod = getCurMethodDecl();
572
573 if (NextToken.is(tok::coloncolon)) {
574 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
575 QualType(), false, SS, 0, false);
576
577 }
578
579 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
580 LookupParsedName(Result, S, &SS, !CurMethod);
581
582 // Perform lookup for Objective-C instance variables (including automatically
583 // synthesized instance variables), if we're in an Objective-C method.
584 // FIXME: This lookup really, really needs to be folded in to the normal
585 // unqualified lookup mechanism.
586 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
587 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000588 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000589 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000590 }
591
592 bool SecondTry = false;
593 bool IsFilteredTemplateName = false;
594
595Corrected:
596 switch (Result.getResultKind()) {
597 case LookupResult::NotFound:
598 // If an unqualified-id is followed by a '(', then we have a function
599 // call.
600 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
601 // In C++, this is an ADL-only call.
602 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000603 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000604 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
605
606 // C90 6.3.2.2:
607 // If the expression that precedes the parenthesized argument list in a
608 // function call consists solely of an identifier, and if no
609 // declaration is visible for this identifier, the identifier is
610 // implicitly declared exactly as if, in the innermost block containing
611 // the function call, the declaration
612 //
613 // extern int identifier ();
614 //
615 // appeared.
616 //
617 // We also allow this in C99 as an extension.
618 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
619 Result.addDecl(D);
620 Result.resolveKind();
621 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
622 }
623 }
624
625 // In C, we first see whether there is a tag type by the same name, in
626 // which case it's likely that the user just forget to write "enum",
627 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000628 if (!getLangOpts().CPlusPlus && !SecondTry &&
629 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
630 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000631 }
632
633 // Perform typo correction to determine if there is another name that is
634 // close to this name.
635 if (!SecondTry) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000636 SecondTry = true;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000637 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain7da8c7d2012-06-29 21:30:39 +0000638 // Try to limit which sets of keywords should be included in typo
639 // correction based on what the next token is.
640 DefaultValidator.WantTypeSpecifiers =
641 NextToken.is(tok::l_paren) || NextToken.is(tok::less) ||
642 NextToken.is(tok::identifier) || NextToken.is(tok::star) ||
643 NextToken.is(tok::amp) || NextToken.is(tok::l_square);
644 DefaultValidator.WantExpressionKeywords =
645 NextToken.is(tok::l_paren) || NextToken.is(tok::identifier) ||
646 NextToken.is(tok::arrow) || NextToken.is(tok::period);
647 DefaultValidator.WantRemainingKeywords =
648 NextToken.is(tok::l_paren) || NextToken.is(tok::semi) ||
649 NextToken.is(tok::identifier) || NextToken.is(tok::l_brace);
650 DefaultValidator.WantCXXNamedCasts = false;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000651 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000652 Result.getLookupKind(), S,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000653 &SS, DefaultValidator)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000654 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
655 unsigned QualifiedDiag = diag::err_no_member_suggest;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000656 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
657 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000658
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000659 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 NamedDecl *UnderlyingFirstDecl
661 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000662 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000663 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000664 UnqualifiedDiag = diag::err_no_template_suggest;
665 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000666 } else if (UnderlyingFirstDecl &&
667 (isa<TypeDecl>(UnderlyingFirstDecl) ||
668 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
669 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000670 UnqualifiedDiag = diag::err_unknown_typename_suggest;
671 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
672 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000673
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000674 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000675 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000676 << Name << CorrectedQuotedStr
677 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000678 else
Douglas Gregor5e16c162011-04-27 03:47:06 +0000679 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000680 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000681 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000682 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000683
684 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000685 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000686
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000687 // Typo correction corrected to a keyword.
688 if (Corrected.isKeyword())
689 return Corrected.getCorrectionAsIdentifierInfo();
690
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000691 // Also update the LookupResult...
692 // FIXME: This should probably go away at some point
693 Result.clear();
694 Result.setLookupName(Corrected.getCorrection());
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000695 if (FirstDecl) {
696 Result.addDecl(FirstDecl);
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000697 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
698 << CorrectedQuotedStr;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000699 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000700
701 // If we found an Objective-C instance variable, let
702 // LookupInObjCMethod build the appropriate expression to
703 // reference the ivar.
704 // FIXME: This is a gross hack.
705 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
706 Result.clear();
707 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
708 return move(E);
709 }
710
711 goto Corrected;
712 }
713 }
714
715 // We failed to correct; just fall through and let the parser deal with it.
716 Result.suppressDiagnostics();
717 return NameClassification::Unknown();
718
Abramo Bagnara7945c982012-01-27 09:46:47 +0000719 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000720 // We performed name lookup into the current instantiation, and there were
721 // dependent bases, so we treat this result the same way as any other
722 // dependent nested-name-specifier.
723
724 // C++ [temp.res]p2:
725 // A name used in a template declaration or definition and that is
726 // dependent on a template-parameter is assumed not to name a type
727 // unless the applicable name lookup finds a type name or the name is
728 // qualified by the keyword typename.
729 //
730 // FIXME: If the next token is '<', we might want to ask the parser to
731 // perform some heroics to see if we actually have a
732 // template-argument-list, which would indicate a missing 'template'
733 // keyword here.
Abramo Bagnara7945c982012-01-27 09:46:47 +0000734 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
735 NameInfo, /*TemplateArgs=*/0);
736 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000737
738 case LookupResult::Found:
739 case LookupResult::FoundOverloaded:
740 case LookupResult::FoundUnresolvedValue:
741 break;
742
743 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000744 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000745 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000746 // C++ [temp.local]p3:
747 // A lookup that finds an injected-class-name (10.2) can result in an
748 // ambiguity in certain cases (for example, if it is found in more than
749 // one base class). If all of the injected-class-names that are found
750 // refer to specializations of the same class template, and if the name
751 // is followed by a template-argument-list, the reference refers to the
752 // class template itself and not a specialization thereof, and is not
753 // ambiguous.
754 //
755 // This filtering can make an ambiguous result into an unambiguous one,
756 // so try again after filtering out template names.
757 FilterAcceptableTemplateNames(Result);
758 if (!Result.isAmbiguous()) {
759 IsFilteredTemplateName = true;
760 break;
761 }
762 }
763
764 // Diagnose the ambiguity and return an error.
765 return NameClassification::Error();
766 }
767
David Blaikiebbafb8a2012-03-11 07:00:24 +0000768 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000769 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
770 // C++ [temp.names]p3:
771 // After name lookup (3.4) finds that a name is a template-name or that
772 // an operator-function-id or a literal- operator-id refers to a set of
773 // overloaded functions any member of which is a function template if
774 // this is followed by a <, the < is always taken as the delimiter of a
775 // template-argument-list and never as the less-than operator.
776 if (!IsFilteredTemplateName)
777 FilterAcceptableTemplateNames(Result);
778
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000779 if (!Result.empty()) {
780 bool IsFunctionTemplate;
781 TemplateName Template;
782 if (Result.end() - Result.begin() > 1) {
783 IsFunctionTemplate = true;
784 Template = Context.getOverloadedTemplateName(Result.begin(),
785 Result.end());
786 } else {
787 TemplateDecl *TD
788 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
789 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
790
791 if (SS.isSet() && !SS.isInvalid())
792 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000793 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000794 TD);
795 else
796 Template = TemplateName(TD);
797 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000798
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000799 if (IsFunctionTemplate) {
800 // Function templates always go through overload resolution, at which
801 // point we'll perform the various checks (e.g., accessibility) we need
802 // to based on which function we selected.
803 Result.suppressDiagnostics();
804
805 return NameClassification::FunctionTemplate(Template);
806 }
807
808 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000809 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000810 }
811
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000812 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000813 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
814 DiagnoseUseOfDecl(Type, NameLoc);
815 QualType T = Context.getTypeDeclType(Type);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000816 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000817 }
818
819 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
820 if (!Class) {
821 // FIXME: It's unfortunate that we don't have a Type node for handling this.
822 if (ObjCCompatibleAliasDecl *Alias
823 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
824 Class = Alias->getClassInterface();
825 }
826
827 if (Class) {
828 DiagnoseUseOfDecl(Class, NameLoc);
829
830 if (NextToken.is(tok::period)) {
831 // Interface. <something> is parsed as a property reference expression.
832 // Just return "unknown" as a fall-through for now.
833 Result.suppressDiagnostics();
834 return NameClassification::Unknown();
835 }
836
837 QualType T = Context.getObjCInterfaceType(Class);
838 return ParsedType::make(T);
839 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000840
841 // Check for a tag type hidden by a non-type decl in a few cases where it
842 // seems likely a type is wanted instead of the non-type that was found.
843 if (!getLangOpts().ObjC1 && FirstDecl && !isa<ClassTemplateDecl>(FirstDecl) &&
844 !isa<TypeAliasTemplateDecl>(FirstDecl)) {
845 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
846 if ((NextToken.is(tok::identifier) ||
847 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
848 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
849 FirstDecl = (*Result.begin())->getUnderlyingDecl();
850 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
851 DiagnoseUseOfDecl(Type, NameLoc);
852 QualType T = Context.getTypeDeclType(Type);
853 return ParsedType::make(T);
854 }
855 }
856 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000857
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000858 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000860
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
862 return BuildDeclarationNameExpr(SS, Result, ADL);
863}
864
John McCall5ed6e8f2009-08-18 00:00:49 +0000865// Determines the context to return to after temporarily entering a
866// context. This depends in an unnecessarily complicated way on the
867// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000868DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000869
John McCall5ed6e8f2009-08-18 00:00:49 +0000870 // Functions defined inline within classes aren't parsed until we've
871 // finished parsing the top-level class, so the top-level class is
872 // the context we'll need to return to.
873 if (isa<FunctionDecl>(DC)) {
874 DC = DC->getLexicalParent();
875
876 // A function not defined within a class will always return to its
877 // lexical context.
878 if (!isa<CXXRecordDecl>(DC))
879 return DC;
880
881 // A C++ inline method/friend is parsed *after* the topmost class
882 // it was declared in is fully parsed ("complete"); the topmost
883 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000884 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885 DC = RD;
886
887 // Return the declaration context of the topmost class the inline method is
888 // declared in.
889 return DC;
890 }
891
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000892 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893}
894
Douglas Gregor91f84212008-12-11 16:49:14 +0000895void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000896 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000897 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000898 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000899 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000900}
901
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000902void Sema::PopDeclContext() {
903 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000904
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000905 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000906 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000907}
908
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000909/// EnterDeclaratorContext - Used when we must lookup names in the context
910/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000911///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000912void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000913 // C++0x [basic.lookup.unqual]p13:
914 // A name used in the definition of a static data member of class
915 // X (after the qualified-id of the static member) is looked up as
916 // if the name was used in a member function of X.
917 // C++0x [basic.lookup.unqual]p14:
918 // If a variable member of a namespace is defined outside of the
919 // scope of its namespace then any name used in the definition of
920 // the variable member (after the declarator-id) is looked up as
921 // if the definition of the variable member occurred in its
922 // namespace.
923 // Both of these imply that we should push a scope whose context
924 // is the semantic context of the declaration. We can't use
925 // PushDeclContext here because that context is not necessarily
926 // lexically contained in the current context. Fortunately,
927 // the containing scope should have the appropriate information.
928
929 assert(!S->getEntity() && "scope already has entity");
930
931#ifndef NDEBUG
932 Scope *Ancestor = S->getParent();
933 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
934 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
935#endif
936
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000937 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000938 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000939}
940
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000941void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000942 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000943
John McCall6df5fef2009-12-19 10:49:29 +0000944 // Switch back to the lexical context. The safety of this is
945 // enforced by an assert in EnterDeclaratorContext.
946 Scope *Ancestor = S->getParent();
947 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
948 CurContext = (DeclContext*) Ancestor->getEntity();
949
950 // We don't need to do anything with the scope, which is going to
951 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952}
953
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000954
955void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
956 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
957 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
958 // We assume that the caller has already called
959 // ActOnReenterTemplateScope
960 FD = TFD->getTemplatedDecl();
961 }
962 if (!FD)
963 return;
964
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000965 // Same implementation as PushDeclContext, but enters the context
966 // from the lexical parent, rather than the top-level class.
967 assert(CurContext == FD->getLexicalParent() &&
968 "The next DeclContext should be lexically contained in the current one.");
969 CurContext = FD;
970 S->setEntity(CurContext);
971
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000972 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
973 ParmVarDecl *Param = FD->getParamDecl(P);
974 // If the parameter has an identifier, then add it to the scope
975 if (Param->getIdentifier()) {
976 S->AddDecl(Param);
977 IdResolver.AddDecl(Param);
978 }
979 }
980}
981
982
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000983void Sema::ActOnExitFunctionContext() {
984 // Same implementation as PopDeclContext, but returns to the lexical parent,
985 // rather than the top-level class.
986 assert(CurContext && "DeclContext imbalance!");
987 CurContext = CurContext->getLexicalParent();
988 assert(CurContext && "Popped translation unit!");
989}
990
991
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992/// \brief Determine whether we allow overloading of the function
993/// PrevDecl with another declaration.
994///
995/// This routine determines whether overloading is possible, not
996/// whether some new function is actually an overload. It will return
997/// true in C++ (where we can always provide overloads) or, as an
998/// extension, in C when the previous function is already an
999/// overloaded function declaration or has the "overloadable"
1000/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001001static bool AllowOverloadingOfFunction(LookupResult &Previous,
1002 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001003 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001004 return true;
1005
John McCall1f82f242009-11-18 22:49:29 +00001006 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001007 return true;
1008
John McCall1f82f242009-11-18 22:49:29 +00001009 return (Previous.getResultKind() == LookupResult::Found
1010 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001011}
1012
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001013/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001014void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001015 // Move up the scope chain until we find the nearest enclosing
1016 // non-transparent context. The declaration will be introduced into this
1017 // scope.
Mike Stump11289f42009-09-09 15:08:12 +00001018 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +00001019 ((DeclContext *)S->getEntity())->isTransparentContext())
1020 S = S->getParent();
1021
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001022 // Add scoped declarations into their context, so that they can be
1023 // found later. Declarations without a context won't be inserted
1024 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001025 if (AddToContext)
1026 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001027
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001028 // Out-of-line definitions shouldn't be pushed into scope in C++.
1029 // Out-of-line variable and function definitions shouldn't even in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001030 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001031 D->isOutOfLine() &&
1032 !D->getDeclContext()->getRedeclContext()->Equals(
1033 D->getLexicalDeclContext()->getRedeclContext()))
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001034 return;
1035
1036 // Template instantiations should also not be pushed into scope.
1037 if (isa<FunctionDecl>(D) &&
1038 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001039 return;
1040
John McCall9f3059a2009-10-09 21:13:30 +00001041 // If this replaces anything in the current scope,
1042 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1043 IEnd = IdResolver.end();
1044 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001045 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1046 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001047 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001048
John McCall9f3059a2009-10-09 21:13:30 +00001049 // Should only need to replace one decl.
1050 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001051 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001052 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001053
John McCall48871652010-08-21 09:40:31 +00001054 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001055
1056 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1057 // Implicitly-generated labels may end up getting generated in an order that
1058 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1059 // the label at the appropriate place in the identifier chain.
1060 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001061 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001062 if (IDC == CurContext) {
1063 if (!S->isDeclScope(*I))
1064 continue;
1065 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001066 break;
1067 }
1068
Douglas Gregor46c04e72011-03-16 16:39:03 +00001069 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001070 } else {
1071 IdResolver.AddDecl(D);
1072 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001073}
1074
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001075void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1076 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1077 TUScope->AddDecl(D);
1078}
1079
Douglas Gregordb446112011-03-07 16:54:27 +00001080bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1081 bool ExplicitInstantiationOrSpecialization) {
1082 return IdResolver.isDeclInScope(D, Ctx, Context, S,
1083 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +00001084}
1085
John McCallcc14d1f2010-08-24 08:50:51 +00001086Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1087 DeclContext *TargetDC = DC->getPrimaryContext();
1088 do {
1089 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1090 if (ScopeDC->getPrimaryContext() == TargetDC)
1091 return S;
1092 } while ((S = S->getParent()));
1093
1094 return 0;
1095}
1096
John McCall1f82f242009-11-18 22:49:29 +00001097static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1098 DeclContext*,
1099 ASTContext&);
1100
1101/// Filters out lookup results that don't fall within the given scope
1102/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00001103void Sema::FilterLookupForScope(LookupResult &R,
1104 DeclContext *Ctx, Scope *S,
1105 bool ConsiderLinkage,
1106 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +00001107 LookupResult::Filter F = R.makeFilter();
1108 while (F.hasNext()) {
1109 NamedDecl *D = F.next();
1110
Richard Smith3f1b5d02011-05-05 21:57:07 +00001111 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +00001112 continue;
1113
1114 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00001115 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001116 continue;
1117
1118 F.erase();
1119 }
1120
1121 F.done();
1122}
1123
1124static bool isUsingDecl(NamedDecl *D) {
1125 return isa<UsingShadowDecl>(D) ||
1126 isa<UnresolvedUsingTypenameDecl>(D) ||
1127 isa<UnresolvedUsingValueDecl>(D);
1128}
1129
1130/// Removes using shadow declarations from the lookup results.
1131static void RemoveUsingDecls(LookupResult &R) {
1132 LookupResult::Filter F = R.makeFilter();
1133 while (F.hasNext())
1134 if (isUsingDecl(F.next()))
1135 F.erase();
1136
1137 F.done();
1138}
1139
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001140/// \brief Check for this common pattern:
1141/// @code
1142/// class S {
1143/// S(const S&); // DO NOT IMPLEMENT
1144/// void operator=(const S&); // DO NOT IMPLEMENT
1145/// };
1146/// @endcode
1147static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1148 // FIXME: Should check for private access too but access is set after we get
1149 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001150 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001151 return false;
1152
1153 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1154 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001155 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1156 return Method->isCopyAssignmentOperator();
1157 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001158}
1159
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001160bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1161 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001162
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001163 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1164 return false;
1165
1166 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001167 if (D->getDeclContext()->isDependentContext() ||
1168 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001169 return false;
1170
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001171 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001172 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1173 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001174
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001175 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1176 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1177 return false;
1178 } else {
1179 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +00001180 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001181 FD->isInlineSpecified())
1182 return false;
1183 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001184
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001185 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001186 Context.DeclMustBeEmitted(FD))
1187 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001188 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1189 if (!VD->isFileVarDecl() ||
1190 VD->getType().isConstant(Context) ||
1191 Context.DeclMustBeEmitted(VD))
1192 return false;
1193
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001194 if (VD->isStaticDataMember() &&
1195 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1196 return false;
1197
John McCalld37d35b2010-10-27 01:41:35 +00001198 } else {
1199 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001200 }
1201
John McCalld37d35b2010-10-27 01:41:35 +00001202 // Only warn for unused decls internal to the translation unit.
1203 if (D->getLinkage() == ExternalLinkage)
1204 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001205
John McCalld37d35b2010-10-27 01:41:35 +00001206 return true;
1207}
1208
1209void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001210 if (!D)
1211 return;
1212
1213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1214 const FunctionDecl *First = FD->getFirstDeclaration();
1215 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1216 return; // First should already be in the vector.
1217 }
1218
1219 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1220 const VarDecl *First = VD->getFirstDeclaration();
1221 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1222 return; // First should already be in the vector.
1223 }
1224
David Blaikie3d8edc22012-05-26 05:35:39 +00001225 if (ShouldWarnIfUnusedFileScopedDecl(D))
1226 UnusedFileScopedDecls.push_back(D);
1227}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001228
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001229static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001230 if (D->isInvalidDecl())
1231 return false;
1232
Eli Friedmanc09e0552012-01-13 23:41:25 +00001233 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001234 return false;
John McCall67da35c2010-02-04 22:26:26 +00001235
Chris Lattnercab02a62011-02-17 20:34:02 +00001236 if (isa<LabelDecl>(D))
1237 return true;
1238
John McCall67da35c2010-02-04 22:26:26 +00001239 // White-list anything that isn't a local variable.
1240 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1241 !D->getDeclContext()->isFunctionOrMethod())
1242 return false;
1243
1244 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001245 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001246
1247 // White-list anything with an __attribute__((unused)) type.
1248 QualType Ty = VD->getType();
1249
1250 // Only look at the outermost level of typedef.
1251 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1252 if (TT->getDecl()->hasAttr<UnusedAttr>())
1253 return false;
1254 }
1255
Douglas Gregor14f232e2010-05-08 23:05:03 +00001256 // If we failed to complete the type for some reason, or if the type is
1257 // dependent, don't diagnose the variable.
1258 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001259 return false;
1260
John McCallcef15822010-03-31 02:47:45 +00001261 if (const TagType *TT = Ty->getAs<TagType>()) {
1262 const TagDecl *Tag = TT->getDecl();
1263 if (Tag->hasAttr<UnusedAttr>())
1264 return false;
1265
1266 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Rafael Espindola7c23b082012-01-06 04:54:01 +00001267 if (!RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001268 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001269
1270 if (const Expr *Init = VD->getInit()) {
1271 const CXXConstructExpr *Construct =
1272 dyn_cast<CXXConstructExpr>(Init);
1273 if (Construct && !Construct->isElidable()) {
1274 CXXConstructorDecl *CD = Construct->getConstructor();
1275 if (!CD->isTrivial())
1276 return false;
1277 }
1278 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001279 }
1280 }
John McCallcef15822010-03-31 02:47:45 +00001281
1282 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001283 }
1284
John McCall67da35c2010-02-04 22:26:26 +00001285 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001286}
1287
Anna Zaks964f4c62011-07-28 20:52:06 +00001288static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1289 FixItHint &Hint) {
1290 if (isa<LabelDecl>(D)) {
1291 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001292 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001293 if (AfterColon.isInvalid())
1294 return;
1295 Hint = FixItHint::CreateRemoval(CharSourceRange::
1296 getCharRange(D->getLocStart(), AfterColon));
1297 }
1298 return;
1299}
1300
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001301/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1302/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001303void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001304 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001305 if (!ShouldDiagnoseUnusedDecl(D))
1306 return;
1307
Anna Zaks964f4c62011-07-28 20:52:06 +00001308 GenerateFixForUnusedDecl(D, Context, Hint);
1309
Chris Lattnercab02a62011-02-17 20:34:02 +00001310 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001311 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001312 DiagID = diag::warn_unused_exception_param;
1313 else if (isa<LabelDecl>(D))
1314 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001315 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001316 DiagID = diag::warn_unused_variable;
1317
Anna Zaks964f4c62011-07-28 20:52:06 +00001318 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001319}
1320
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001321static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1322 // Verify that we have no forward references left. If so, there was a goto
1323 // or address of a label taken, but no definition of it. Label fwd
1324 // definitions are indicated with a null substmt.
1325 if (L->getStmt() == 0)
1326 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1327}
1328
Steve Naroffc62adb62007-10-09 22:01:59 +00001329void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001330 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001331 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001332 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001333
Chris Lattner302b4be2006-11-19 02:31:38 +00001334 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1335 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001336 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001337 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001338
Douglas Gregor91f84212008-12-11 16:49:14 +00001339 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1340 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001341
Douglas Gregor91f84212008-12-11 16:49:14 +00001342 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001343
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001344 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001345 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001346 DiagnoseUnusedDecl(D);
1347
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001348 // If this was a forward reference to a label, verify it was defined.
1349 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1350 CheckPoppedLabel(LD, *this);
1351
Douglas Gregor91f84212008-12-11 16:49:14 +00001352 // Remove this name from our lexical scope.
1353 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001354 }
1355}
1356
James Molloy6f8780b2012-02-29 10:24:19 +00001357void Sema::ActOnStartFunctionDeclarator() {
1358 ++InFunctionDeclarator;
1359}
1360
1361void Sema::ActOnEndFunctionDeclarator() {
1362 assert(InFunctionDeclarator);
1363 --InFunctionDeclarator;
1364}
1365
Douglas Gregor1c283312010-08-11 12:19:30 +00001366/// \brief Look for an Objective-C class in the translation unit.
1367///
1368/// \param Id The name of the Objective-C class we're looking for. If
1369/// typo-correction fixes this name, the Id will be updated
1370/// to the fixed name.
1371///
1372/// \param IdLoc The location of the name in the translation unit.
1373///
James Dennett41725122012-06-22 10:16:05 +00001374/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001375/// if there is no class with the given name.
1376///
1377/// \returns The declaration of the named Objective-C class, or NULL if the
1378/// class could not be found.
1379ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1380 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001381 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001382 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1383 // creation from this context.
1384 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1385
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001386 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001387 // Perform typo correction at the given location, but only if we
1388 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001389 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1390 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1391 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001392 Validator)) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001393 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001394 Diag(IdLoc, diag::err_undef_interface_suggest)
1395 << Id << IDecl->getDeclName()
1396 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1397 Diag(IDecl->getLocation(), diag::note_previous_decl)
1398 << IDecl->getDeclName();
1399
1400 Id = IDecl->getIdentifier();
1401 }
1402 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001403 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1404 // This routine must always return a class definition, if any.
1405 if (Def && Def->getDefinition())
1406 Def = Def->getDefinition();
1407 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001408}
1409
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001410/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1411/// from S, where a non-field would be declared. This routine copes
1412/// with the difference between C and C++ scoping rules in structs and
1413/// unions. For example, the following code is well-formed in C but
1414/// ill-formed in C++:
1415/// @code
1416/// struct S6 {
1417/// enum { BAR } e;
1418/// };
Mike Stump11289f42009-09-09 15:08:12 +00001419///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001420/// void test_S6() {
1421/// struct S6 a;
1422/// a.e = BAR;
1423/// }
1424/// @endcode
1425/// For the declaration of BAR, this routine will return a different
1426/// scope. The scope S will be the scope of the unnamed enumeration
1427/// within S6. In C++, this routine will return the scope associated
1428/// with S6, because the enumeration's scope is a transparent
1429/// context but structures can contain non-field names. In C, this
1430/// routine will return the translation unit scope, since the
1431/// enumeration's scope is a transparent context and structures cannot
1432/// contain non-field names.
1433Scope *Sema::getNonFieldDeclScope(Scope *S) {
1434 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001435 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001436 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001437 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001438 S = S->getParent();
1439 return S;
1440}
1441
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001442/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1443/// file scope. lazily create a decl for it. ForRedeclaration is true
1444/// if we're creating this built-in in anticipation of redeclaring the
1445/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001446NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001447 Scope *S, bool ForRedeclaration,
1448 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001449 Builtin::ID BID = (Builtin::ID)bid;
1450
Chris Lattnerecd79c62009-06-14 00:45:47 +00001451 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001452 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001453 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001454 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001455 // Okay
1456 break;
1457
Mike Stump93246cc2009-07-28 23:57:15 +00001458 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001459 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001460 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001461 << Context.BuiltinInfo.GetName(BID);
1462 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001463
Mike Stump93246cc2009-07-28 23:57:15 +00001464 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001465 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001466 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001467 << Context.BuiltinInfo.GetName(BID);
1468 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001469
1470 case ASTContext::GE_Missing_ucontext:
1471 if (ForRedeclaration)
1472 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1473 << Context.BuiltinInfo.GetName(BID);
1474 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001475 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001476
1477 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1478 Diag(Loc, diag::ext_implicit_lib_function_decl)
1479 << Context.BuiltinInfo.GetName(BID)
1480 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001481 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001482 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001483 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001484 Diag(Loc, diag::note_please_include_header)
1485 << Context.BuiltinInfo.getHeaderName(BID)
1486 << Context.BuiltinInfo.GetName(BID);
1487 }
1488
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001489 FunctionDecl *New = FunctionDecl::Create(Context,
1490 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001491 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001492 SC_Extern,
1493 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001494 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001495 New->setImplicit();
1496
Chris Lattner4dd27102008-05-05 22:18:14 +00001497 // Create Decl objects for each parameter, adding them to the
1498 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001499 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001500 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001501 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1502 ParmVarDecl *parm =
1503 ParmVarDecl::Create(Context, New, SourceLocation(),
1504 SourceLocation(), 0,
1505 FT->getArgType(i), /*TInfo=*/0,
1506 SC_None, SC_None, 0);
1507 parm->setScopeInfo(0, i);
1508 Params.push_back(parm);
1509 }
David Blaikie9c70e042011-09-21 18:16:56 +00001510 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512
1513 AddKnownFunctionAttributes(New);
1514
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001515 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001516 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1517 // relate Scopes to DeclContexts, and probably eliminate CurContext
1518 // entirely, but we're not there yet.
1519 DeclContext *SavedContext = CurContext;
1520 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001521 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001522 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001523 return New;
1524}
1525
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001526bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1527 QualType OldType;
1528 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1529 OldType = OldTypedef->getUnderlyingType();
1530 else
1531 OldType = Context.getTypeDeclType(Old);
1532 QualType NewType = New->getUnderlyingType();
1533
Douglas Gregoraab36982012-01-11 22:33:48 +00001534 if (NewType->isVariablyModifiedType()) {
1535 // Must not redefine a typedef with a variably-modified type.
1536 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1537 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1538 << Kind << NewType;
1539 if (Old->getLocation().isValid())
1540 Diag(Old->getLocation(), diag::note_previous_definition);
1541 New->setInvalidDecl();
1542 return true;
1543 }
1544
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001545 if (OldType != NewType &&
1546 !OldType->isDependentType() &&
1547 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001548 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001549 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1550 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1551 << Kind << NewType << OldType;
1552 if (Old->getLocation().isValid())
1553 Diag(Old->getLocation(), diag::note_previous_definition);
1554 New->setInvalidDecl();
1555 return true;
1556 }
1557 return false;
1558}
1559
Richard Smithdda56e42011-04-15 14:24:37 +00001560/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001561/// same name and scope as a previous declaration 'Old'. Figure out
1562/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001563/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001564///
Richard Smithdda56e42011-04-15 14:24:37 +00001565void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001566 // If the new decl is known invalid already, don't bother doing any
1567 // merging checks.
1568 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001569
Steve Naroff44cfcb62008-09-09 14:32:20 +00001570 // Allow multiple definitions for ObjC built-in typedefs.
1571 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001572 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001573 const IdentifierInfo *TypeID = New->getIdentifier();
1574 switch (TypeID->getLength()) {
1575 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001576 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001577 {
1578 if (!TypeID->isStr("id"))
1579 break;
1580 QualType T = New->getUnderlyingType();
1581 if (!T->isPointerType())
1582 break;
1583 if (!T->isVoidPointerType()) {
1584 QualType PT = T->getAs<PointerType>()->getPointeeType();
1585 if (!PT->isStructureType())
1586 break;
1587 }
1588 Context.setObjCIdRedefinitionType(T);
1589 // Install the built-in type for 'id', ignoring the current definition.
1590 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1591 return;
1592 }
Chris Lattner66e32812008-11-20 05:41:43 +00001593 case 5:
1594 if (!TypeID->isStr("Class"))
1595 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001596 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001597 // Install the built-in type for 'Class', ignoring the current definition.
1598 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001599 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001600 case 3:
1601 if (!TypeID->isStr("SEL"))
1602 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001603 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001604 // Install the built-in type for 'SEL', ignoring the current definition.
1605 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001606 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001607 }
1608 // Fall through - the typedef name was not a builtin type.
1609 }
John McCall1f82f242009-11-18 22:49:29 +00001610
Douglas Gregorfb034662009-01-28 17:15:10 +00001611 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001612 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1613 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001614 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001615 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001616
1617 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001618 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001619 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001620
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001621 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001622 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001623
John McCall1f82f242009-11-18 22:49:29 +00001624 // If the old declaration is invalid, just give up here.
1625 if (Old->isInvalidDecl())
1626 return New->setInvalidDecl();
1627
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001628 // If the typedef types are not identical, reject them in all languages and
1629 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001630 if (isIncompatibleTypedef(Old, New))
1631 return;
Mike Stump11289f42009-09-09 15:08:12 +00001632
John McCall91f1a022009-12-30 00:31:22 +00001633 // The types match. Link up the redeclaration chain if the old
1634 // declaration was a typedef.
Richard Smithdda56e42011-04-15 14:24:37 +00001635 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1636 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001637
David Blaikiebbafb8a2012-03-11 07:00:24 +00001638 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001639 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001640
David Blaikiebbafb8a2012-03-11 07:00:24 +00001641 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001642 // C++ [dcl.typedef]p2:
1643 // In a given non-class scope, a typedef specifier can be used to
1644 // redefine the name of any type declared in that scope to refer
1645 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001646 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001647 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001648
1649 // C++0x [dcl.typedef]p4:
1650 // In a given class scope, a typedef specifier can be used to redefine
1651 // any class-name declared in that scope that is not also a typedef-name
1652 // to refer to the type to which it already refers.
1653 //
1654 // This wording came in via DR424, which was a correction to the
1655 // wording in DR56, which accidentally banned code like:
1656 //
1657 // struct S {
1658 // typedef struct A { } A;
1659 // };
1660 //
1661 // in the C++03 standard. We implement the C++0x semantics, which
1662 // allow the above but disallow
1663 //
1664 // struct S {
1665 // typedef int I;
1666 // typedef int I;
1667 // };
1668 //
1669 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001670 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001671 return;
1672
Chris Lattner2581fc32009-04-17 22:04:20 +00001673 Diag(New->getLocation(), diag::err_redefinition)
1674 << New->getDeclName();
1675 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001676 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001677 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001678
Douglas Gregor7363fb02012-01-11 04:25:01 +00001679 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001680 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001681 return;
1682
Chris Lattner2581fc32009-04-17 22:04:20 +00001683 // If we have a redefinition of a typedef in C, emit a warning. This warning
1684 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001685 // -Wtypedef-redefinition. If either the original or the redefinition is
1686 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001687 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001688 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1689 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001690 return;
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattner2581fc32009-04-17 22:04:20 +00001692 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1693 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001694 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001695 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001696}
1697
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001698/// DeclhasAttr - returns true if decl Declaration already has the target
1699/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001700static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001701DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001702 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1703 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1704 // responsible for making sure they are consistent.
1705 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1706 if (AA)
1707 return false;
1708
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001709 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001710 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001711 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1712 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001713 if (Ann) {
1714 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1715 return true;
1716 continue;
1717 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001718 // FIXME: Don't hardcode this check
1719 if (OA && isa<OwnershipAttr>(*i))
1720 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001721 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001722 }
Chris Lattner84966392008-03-03 03:28:21 +00001723
1724 return false;
1725}
1726
Rafael Espindolac67f2232012-05-10 02:50:16 +00001727bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001728 InheritableAttr *NewAttr = NULL;
Rafael Espindolac67f2232012-05-10 02:50:16 +00001729 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001730 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1731 AA->getIntroduced(), AA->getDeprecated(),
1732 AA->getObsoleted(), AA->getUnavailable(),
1733 AA->getMessage());
1734 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1735 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
1736 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1737 NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
1738 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1739 NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
1740 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1741 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
1742 FA->getFormatIdx(), FA->getFirstArg());
1743 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1744 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
1745 else if (!DeclHasAttr(D, Attr))
1746 NewAttr = cast<InheritableAttr>(Attr->clone(Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001747
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001748 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001749 NewAttr->setInherited(true);
1750 D->addAttr(NewAttr);
1751 return true;
1752 }
1753
1754 return false;
1755}
1756
Rafael Espindola36191042012-05-18 01:47:00 +00001757static const Decl *getDefinition(Decl *D) {
1758 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1759 return TD->getDefinition();
1760 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1761 return VD->getDefinition();
1762 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1763 const FunctionDecl* Def;
1764 if (FD->hasBody(Def))
1765 return Def;
1766 }
1767 return NULL;
1768}
1769
John McCallf79e87d2011-03-02 04:00:57 +00001770/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Douglas Gregor32c17572012-01-01 20:30:41 +00001771void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1772 bool MergeDeprecation) {
Rafael Espindola36191042012-05-18 01:47:00 +00001773 // attributes declared post-definition are currently ignored
1774 const Decl *Def = getDefinition(Old);
1775 if (Def && Def != New && New->hasAttrs()) {
1776 Diag(New->getLocation(), diag::warn_attribute_precede_definition);
1777 Diag(Def->getLocation(), diag::note_previous_definition);
1778 New->dropAttrs();
1779 }
1780
Douglas Gregor32c17572012-01-01 20:30:41 +00001781 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001782 return;
John McCallf79e87d2011-03-02 04:00:57 +00001783
Douglas Gregor32c17572012-01-01 20:30:41 +00001784 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00001785
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001786 // Ensure that any moving of objects within the allocated map is done before
1787 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00001788 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00001789
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001790 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00001791 i = Old->specific_attr_begin<InheritableAttr>(),
1792 e = Old->specific_attr_end<InheritableAttr>();
1793 i != e; ++i) {
Douglas Gregorb1fa1482011-09-23 20:23:42 +00001794 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor32c17572012-01-01 20:30:41 +00001795 if (!MergeDeprecation &&
Douglas Gregorb1fa1482011-09-23 20:23:42 +00001796 (isa<DeprecatedAttr>(*i) ||
1797 isa<UnavailableAttr>(*i) ||
1798 isa<AvailabilityAttr>(*i)))
John McCalld2930c22011-07-22 02:45:48 +00001799 continue;
1800
Rafael Espindolac67f2232012-05-10 02:50:16 +00001801 if (mergeDeclAttribute(New, *i))
John McCallf79e87d2011-03-02 04:00:57 +00001802 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001803 }
John McCallf79e87d2011-03-02 04:00:57 +00001804
Douglas Gregor32c17572012-01-01 20:30:41 +00001805 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00001806}
1807
1808/// mergeParamDeclAttributes - Copy attributes from the old parameter
1809/// to the new one.
1810static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1811 const ParmVarDecl *oldDecl,
1812 ASTContext &C) {
1813 if (!oldDecl->hasAttrs())
1814 return;
1815
1816 bool foundAny = newDecl->hasAttrs();
1817
1818 // Ensure that any moving of objects within the allocated map is
1819 // done before we process them.
1820 if (!foundAny) newDecl->setAttrs(AttrVec());
1821
1822 for (specific_attr_iterator<InheritableParamAttr>
1823 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1824 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1825 if (!DeclHasAttr(newDecl, *i)) {
1826 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1827 newAttr->setInherited(true);
1828 newDecl->addAttr(newAttr);
1829 foundAny = true;
1830 }
1831 }
1832
1833 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001834}
1835
Dan Gohman28ade552010-07-26 21:25:24 +00001836namespace {
1837
Douglas Gregora74a2972009-03-06 22:43:54 +00001838/// Used in MergeFunctionDecl to keep track of function parameters in
1839/// C.
1840struct GNUCompatibleParamWarning {
1841 ParmVarDecl *OldParm;
1842 ParmVarDecl *NewParm;
1843 QualType PromotedType;
1844};
1845
Dan Gohman28ade552010-07-26 21:25:24 +00001846}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001847
1848/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001849Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001850 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001851 if (Ctor->isDefaultConstructor())
1852 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001853
1854 if (Ctor->isCopyConstructor())
1855 return Sema::CXXCopyConstructor;
1856
1857 if (Ctor->isMoveConstructor())
1858 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001859 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001860 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001861 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001862 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00001863 } else if (MD->isMoveAssignmentOperator()) {
1864 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001865 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001866
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001867 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001868}
1869
Sebastian Redl243d9052010-06-09 21:17:41 +00001870/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001871/// only extern inline functions can be redefined, and even then only in
1872/// GNU89 mode.
1873static bool canRedefineFunction(const FunctionDecl *FD,
1874 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001875 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1876 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001877 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001878 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001879}
1880
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001881/// MergeFunctionDecl - We just parsed a function 'New' from
1882/// declarator D which has the same name and scope as a previous
1883/// declaration 'Old'. Figure out how to resolve this situation,
1884/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001885///
1886/// In C++, New and Old must be declarations that are not
1887/// overloaded. Use IsOverload to determine whether New and Old are
1888/// overloaded, and to select the Old declaration that New should be
1889/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001890///
1891/// Returns true if there was an error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +00001892bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001893 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001894 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001895 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001896 = dyn_cast<FunctionTemplateDecl>(OldD))
1897 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001898 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001899 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001900 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001901 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1902 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1903 Diag(Shadow->getTargetDecl()->getLocation(),
1904 diag::note_using_decl_target);
1905 Diag(Shadow->getUsingDecl()->getLocation(),
1906 diag::note_using_decl) << 0;
1907 return true;
1908 }
1909
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001910 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001911 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001912 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001913 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001914 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001915
1916 // Determine whether the previous declaration was a definition,
1917 // implicit declaration, or a declaration.
1918 diag::kind PrevDiag;
1919 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001920 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001921 else if (Old->isImplicit())
1922 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001923 else
Chris Lattner0369c572008-11-23 23:12:31 +00001924 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001925
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001926 QualType OldQType = Context.getCanonicalType(Old->getType());
1927 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001928
Charles Davisfea48452010-02-18 02:00:42 +00001929 // Don't complain about this if we're in GNU89 mode and the old function
1930 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001931 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001932 New->getStorageClass() == SC_Static &&
1933 Old->getStorageClass() != SC_Static &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001934 !canRedefineFunction(Old, getLangOpts())) {
1935 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00001936 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1937 Diag(Old->getLocation(), PrevDiag);
1938 } else {
1939 Diag(New->getLocation(), diag::err_static_non_static) << New;
1940 Diag(Old->getLocation(), PrevDiag);
1941 return true;
1942 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00001943 }
1944
John McCallcddbad02010-02-04 05:44:44 +00001945 // If a function is first declared with a calling convention, but is
1946 // later declared or defined without one, the second decl assumes the
1947 // calling convention of the first.
1948 //
1949 // For the new decl, we have to look at the NON-canonical type to tell the
1950 // difference between a function that really doesn't have a calling
1951 // convention and one that is declared cdecl. That's because in
1952 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1953 // because it is the default calling convention.
1954 //
1955 // Note also that we DO NOT return at this point, because we still have
1956 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001957 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001958 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001959 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1960 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1961 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001962 if (OldTypeInfo.getCC() != CC_Default &&
1963 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001964 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1965 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001966 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1967 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001968 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001969 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001970 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1971 << (OldTypeInfo.getCC() == CC_Default)
1972 << (OldTypeInfo.getCC() == CC_Default ? "" :
1973 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001974 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001975 return true;
1976 }
1977
John McCallab26cfa2010-02-05 21:31:56 +00001978 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001979 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1980 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1981 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001982 }
1983
Douglas Gregor77e274f2010-06-18 21:30:25 +00001984 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00001985 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1986 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1987 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001988 Diag(New->getLocation(), diag::err_regparm_mismatch)
1989 << NewType->getRegParmType()
1990 << OldType->getRegParmType();
1991 Diag(Old->getLocation(), diag::note_previous_declaration);
1992 return true;
1993 }
John McCall4f5019e2010-12-19 02:44:49 +00001994
1995 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1996 RequiresAdjustment = true;
1997 }
1998
Douglas Gregorf1404d72011-10-14 15:55:40 +00001999 // Merge ns_returns_retained attribute.
2000 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2001 if (NewTypeInfo.getProducesResult()) {
2002 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2003 Diag(Old->getLocation(), diag::note_previous_declaration);
2004 return true;
2005 }
2006
2007 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2008 RequiresAdjustment = true;
2009 }
2010
John McCall4f5019e2010-12-19 02:44:49 +00002011 if (RequiresAdjustment) {
2012 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2013 New->setType(QualType(NewType, 0));
2014 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00002015 }
2016
David Blaikiebbafb8a2012-03-11 07:00:24 +00002017 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 // (C++98 13.1p2):
2019 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002020 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002021 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00002022 QualType OldReturnType = OldType->getResultType();
2023 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002024 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002025 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002026 if (NewReturnType->isObjCObjectPointerType()
2027 && OldReturnType->isObjCObjectPointerType())
2028 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2029 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002030 if (New->isCXXClassMember() && New->isOutOfLine())
2031 Diag(New->getLocation(),
2032 diag::err_member_def_does_not_match_ret_type) << New;
2033 else
2034 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002035 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2036 return true;
2037 }
2038 else
2039 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002040 }
2041
2042 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00002043 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002044 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002045 // Preserve triviality.
2046 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002047
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002048 // MSVC allows explicit template specialization at class scope:
2049 // 2 CXMethodDecls referring to the same function will be injected.
2050 // We don't want a redeclartion error.
2051 bool IsClassScopeExplicitSpecialization =
2052 OldMethod->isFunctionTemplateSpecialization() &&
2053 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002054 bool isFriend = NewMethod->getFriendObjectKind();
2055
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002056 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2057 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002058 // -- Member function declarations with the same name and the
2059 // same parameter types cannot be overloaded if any of them
2060 // is a static member function declaration.
2061 if (OldMethod->isStatic() || NewMethod->isStatic()) {
2062 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2063 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2064 return true;
2065 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002066
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002067 // C++ [class.mem]p1:
2068 // [...] A member shall not be declared twice in the
2069 // member-specification, except that a nested class or member
2070 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002071 if (ActiveTemplateInstantiations.empty()) {
2072 unsigned NewDiag;
2073 if (isa<CXXConstructorDecl>(OldMethod))
2074 NewDiag = diag::err_constructor_redeclared;
2075 else if (isa<CXXDestructorDecl>(NewMethod))
2076 NewDiag = diag::err_destructor_redeclared;
2077 else if (isa<CXXConversionDecl>(NewMethod))
2078 NewDiag = diag::err_conv_function_redeclared;
2079 else
2080 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002081
Richard Smith57e7ff92012-07-13 04:12:04 +00002082 Diag(New->getLocation(), NewDiag);
2083 } else {
2084 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2085 << New << New->getType();
2086 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002087 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002088
2089 // Complain if this is an explicit declaration of a special
2090 // member that was initially declared implicitly.
2091 //
2092 // As an exception, it's okay to befriend such methods in order
2093 // to permit the implicit constructor/destructor/operator calls.
2094 } else if (OldMethod->isImplicit()) {
2095 if (isFriend) {
2096 NewMethod->setImplicit();
2097 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002098 Diag(NewMethod->getLocation(),
2099 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002100 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002101 return true;
2102 }
Richard Smith337a5a12012-06-08 01:30:54 +00002103 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002104 Diag(NewMethod->getLocation(),
2105 diag::err_definition_of_explicitly_defaulted_member)
2106 << getSpecialMember(OldMethod);
2107 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108 }
2109 }
2110
2111 // (C++98 8.3.5p3):
2112 // All declarations for a function shall agree exactly in both the
2113 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002114 // We also want to respect all the extended bits except noreturn.
2115
2116 // noreturn should now match unless the old type info didn't have it.
2117 QualType OldQTypeForComparison = OldQType;
2118 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2119 assert(OldQType == QualType(OldType, 0));
2120 const FunctionType *OldTypeForComparison
2121 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2122 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2123 assert(OldQTypeForComparison.isCanonical());
2124 }
2125
2126 if (OldQTypeForComparison == NewQType)
James Molloye9430032012-03-13 08:55:35 +00002127 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002128
2129 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002130 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002131
2132 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002133 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002134 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002135 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002136 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2137 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002138 const FunctionProtoType *OldProto = 0;
2139 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002140 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002141 // The old declaration provided a function prototype, but the
2142 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002143 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002144 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002145 OldProto->arg_type_end());
2146 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00002147 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00002148 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002149 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002150 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002151
2152 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002153 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002154 for (FunctionProtoType::arg_type_iterator
2155 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002156 ParamEnd = OldProto->arg_type_end();
2157 ParamType != ParamEnd; ++ParamType) {
2158 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002159 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002160 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002161 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00002162 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002163 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002164 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002165 Param->setImplicit();
2166 Params.push_back(Param);
2167 }
2168
David Blaikie9c70e042011-09-21 18:16:56 +00002169 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002170 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002171
James Molloye9430032012-03-13 08:55:35 +00002172 return MergeCompatibleFunctionDecls(New, Old, S);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002173 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002174
Douglas Gregora74a2972009-03-06 22:43:54 +00002175 // GNU C permits a K&R definition to follow a prototype declaration
2176 // if the declared types of the parameters in the K&R definition
2177 // match the types in the prototype declaration, even when the
2178 // promoted types of the parameters from the K&R definition differ
2179 // from the types in the prototype. GCC then keeps the types from
2180 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002181 //
2182 // If a variadic prototype is followed by a non-variadic K&R definition,
2183 // the K&R definition becomes variadic. This is sort of an edge case, but
2184 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2185 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002186 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002187 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002188 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002189 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002190 SmallVector<QualType, 16> ArgTypes;
2191 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002192 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002193 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002194 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002195 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregora74a2972009-03-06 22:43:54 +00002197 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002198 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2199 NewProto->getResultType());
2200 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002201 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002202 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002203 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2204 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002205 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002206 NewProto->getArgType(Idx))) {
2207 ArgTypes.push_back(NewParm->getType());
2208 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002209 NewParm->getType(),
2210 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002211 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002212 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2213 Warnings.push_back(Warn);
2214 ArgTypes.push_back(NewParm->getType());
2215 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002216 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002217 }
2218
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002219 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002220 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2221 Diag(Warnings[Warn].NewParm->getLocation(),
2222 diag::ext_param_promoted_not_compatible_with_prototype)
2223 << Warnings[Warn].PromotedType
2224 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002225 if (Warnings[Warn].OldParm->getLocation().isValid())
2226 Diag(Warnings[Warn].OldParm->getLocation(),
2227 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002228 }
2229
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002230 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2231 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00002232 OldProto->getExtProtoInfo()));
James Molloye9430032012-03-13 08:55:35 +00002233 return MergeCompatibleFunctionDecls(New, Old, S);
Douglas Gregora74a2972009-03-06 22:43:54 +00002234 }
2235
2236 // Fall through to diagnose conflicting types.
2237 }
2238
Steve Naroff17832a42008-01-16 15:01:34 +00002239 // A function that has already been declared has been redeclared or defined
2240 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00002241 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002242 // The user has declared a builtin function with an incompatible
2243 // signature.
2244 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2245 // The function the user is redeclaring is a library-defined
2246 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00002247 // redeclaration, then pretend that we don't know about this
2248 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002249 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2250 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2251 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00002252 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2253 Old->setInvalidDecl();
2254 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002255 }
Steve Naroff17832a42008-01-16 15:01:34 +00002256
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002257 PrevDiag = diag::note_previous_builtin_declaration;
2258 }
2259
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002260 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002261 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002262 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002263}
2264
Douglas Gregore62c0a42009-02-24 01:23:02 +00002265/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002266/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002267///
2268/// This routine handles the merging of attributes and other
2269/// properties of function declarations form the old declaration to
2270/// the new declaration, once we know that New is in fact a
2271/// redeclaration of Old.
2272///
2273/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002274bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2275 Scope *S) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002276 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002277 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002278
2279 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00002280 if (Old->getStorageClass() != SC_Extern &&
2281 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002282 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00002283
Douglas Gregore62c0a42009-02-24 01:23:02 +00002284 // Merge "pure" flag.
2285 if (Old->isPure())
2286 New->setPure();
2287
John McCallf79e87d2011-03-02 04:00:57 +00002288 // Merge attributes from the parameters. These can mismatch with K&R
2289 // declarations.
2290 if (New->getNumParams() == Old->getNumParams())
2291 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2292 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2293 Context);
2294
David Blaikiebbafb8a2012-03-11 07:00:24 +00002295 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002296 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002297
2298 return false;
2299}
2300
John McCall31168b02011-06-15 23:02:42 +00002301
John McCallf79e87d2011-03-02 04:00:57 +00002302void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002303 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002304
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002305 // Merge the attributes, including deprecated/unavailable
2306 mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
John McCallf79e87d2011-03-02 04:00:57 +00002307
2308 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002309 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2310 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002311 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002312 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002313 ni != ne && oi != oe; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00002314 mergeParamDeclAttributes(*ni, *oi, Context);
John McCalld2930c22011-07-22 02:45:48 +00002315
Douglas Gregor33823722011-06-11 01:09:30 +00002316 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00002317}
2318
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002319/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2320/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002321/// emitting diagnostics as appropriate.
2322///
2323/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002324/// to here in AddInitializerToDecl. We can't check them before the initializer
2325/// is attached.
Richard Smith30482bc2011-02-20 03:19:35 +00002326void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2327 if (New->isInvalidDecl() || Old->isInvalidDecl())
2328 return;
2329
2330 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002331 if (getLangOpts().CPlusPlus) {
Richard Smith30482bc2011-02-20 03:19:35 +00002332 AutoType *AT = New->getType()->getContainedAutoType();
2333 if (AT && !AT->isDeduced()) {
2334 // We don't know what the new type is until the initializer is attached.
2335 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002336 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2337 // These could still be something that needs exception specs checked.
2338 return MergeVarDeclExceptionSpecs(New, Old);
2339 }
Richard Smith30482bc2011-02-20 03:19:35 +00002340 // C++ [basic.link]p10:
2341 // [...] the types specified by all declarations referring to a given
2342 // object or function shall be identical, except that declarations for an
2343 // array object can specify array types that differ by the presence or
2344 // absence of a major array bound (8.3.4).
2345 else if (Old->getType()->isIncompleteArrayType() &&
2346 New->getType()->isArrayType()) {
2347 CanQual<ArrayType> OldArray
2348 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2349 CanQual<ArrayType> NewArray
2350 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2351 if (OldArray->getElementType() == NewArray->getElementType())
2352 MergedT = New->getType();
2353 } else if (Old->getType()->isArrayType() &&
2354 New->getType()->isIncompleteArrayType()) {
2355 CanQual<ArrayType> OldArray
2356 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2357 CanQual<ArrayType> NewArray
2358 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2359 if (OldArray->getElementType() == NewArray->getElementType())
2360 MergedT = Old->getType();
2361 } else if (New->getType()->isObjCObjectPointerType()
2362 && Old->getType()->isObjCObjectPointerType()) {
2363 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2364 Old->getType());
2365 }
2366 } else {
2367 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2368 }
2369 if (MergedT.isNull()) {
2370 Diag(New->getLocation(), diag::err_redefinition_different_type)
2371 << New->getDeclName();
2372 Diag(Old->getLocation(), diag::note_previous_definition);
2373 return New->setInvalidDecl();
2374 }
2375 New->setType(MergedT);
2376}
2377
Chris Lattner01564d92007-01-27 19:27:06 +00002378/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2379/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2380/// situation, merging decls or emitting diagnostics as appropriate.
2381///
Mike Stump11289f42009-09-09 15:08:12 +00002382/// Tentative definition rules (C99 6.9.2p2) are checked by
2383/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002384/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002385///
John McCall1f82f242009-11-18 22:49:29 +00002386void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2387 // If the new decl is already invalid, don't do any other checking.
2388 if (New->isInvalidDecl())
2389 return;
Mike Stump11289f42009-09-09 15:08:12 +00002390
Chris Lattnerc511efb2007-01-27 19:32:14 +00002391 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002392 VarDecl *Old = 0;
2393 if (!Previous.isSingleResult() ||
2394 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002395 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002396 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002397 Diag(Previous.getRepresentativeDecl()->getLocation(),
2398 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002399 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002400 }
Chris Lattner84966392008-03-03 03:28:21 +00002401
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002402 // C++ [class.mem]p1:
2403 // A member shall not be declared twice in the member-specification [...]
2404 //
2405 // Here, we need only consider static data members.
2406 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2407 Diag(New->getLocation(), diag::err_duplicate_member)
2408 << New->getIdentifier();
2409 Diag(Old->getLocation(), diag::note_previous_declaration);
2410 New->setInvalidDecl();
2411 }
2412
Douglas Gregor32c17572012-01-01 20:30:41 +00002413 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00002414 // Warn if an already-declared variable is made a weak_import in a subsequent
2415 // declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002416 if (New->getAttr<WeakImportAttr>() &&
2417 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002418 !Old->getAttr<WeakImportAttr>()) {
2419 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2420 Diag(Old->getLocation(), diag::note_previous_definition);
2421 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002422 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002423 }
Chris Lattner84966392008-03-03 03:28:21 +00002424
Richard Smith30482bc2011-02-20 03:19:35 +00002425 // Merge the types.
2426 MergeVarDeclTypes(New, Old);
2427 if (New->isInvalidDecl())
2428 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002429
Steve Naroff1e787362008-01-30 00:44:01 +00002430 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002431 if (New->getStorageClass() == SC_Static &&
2432 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002433 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002434 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002435 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002436 }
Mike Stump11289f42009-09-09 15:08:12 +00002437 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002438 // For an identifier declared with the storage-class specifier
2439 // extern in a scope in which a prior declaration of that
2440 // identifier is visible,23) if the prior declaration specifies
2441 // internal or external linkage, the linkage of the identifier at
2442 // the later declaration is the same as the linkage specified at
2443 // the prior declaration. If no prior declaration is visible, or
2444 // if the prior declaration specifies no linkage, then the
2445 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002446 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002447 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002448 else if (New->getStorageClass() != SC_Static &&
2449 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002450 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002451 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002452 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002453 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002454
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002455 // Check if extern is followed by non-extern and vice-versa.
2456 if (New->hasExternalStorage() &&
2457 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2458 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2459 Diag(Old->getLocation(), diag::note_previous_definition);
2460 return New->setInvalidDecl();
2461 }
2462 if (Old->hasExternalStorage() &&
2463 !New->hasLinkage() && New->isLocalVarDecl()) {
2464 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2465 Diag(Old->getLocation(), diag::note_previous_definition);
2466 return New->setInvalidDecl();
2467 }
2468
Steve Naroffa5629372008-09-17 14:05:40 +00002469 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002470
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002471 // FIXME: The test for external storage here seems wrong? We still
2472 // need to check for mismatches.
2473 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002474 // Don't complain about out-of-line definitions of static members.
2475 !(Old->getLexicalDeclContext()->isRecord() &&
2476 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002477 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002478 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002479 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002480 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002481
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002482 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2483 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2484 Diag(Old->getLocation(), diag::note_previous_definition);
2485 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2486 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2487 Diag(Old->getLocation(), diag::note_previous_definition);
2488 }
2489
Sebastian Redlf1842912010-02-02 18:35:11 +00002490 // C++ doesn't have tentative definitions, so go right ahead and check here.
2491 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002492 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00002493 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002494 (Def = Old->getDefinition())) {
2495 Diag(New->getLocation(), diag::err_redefinition)
2496 << New->getDeclName();
2497 Diag(Def->getLocation(), diag::note_previous_definition);
2498 New->setInvalidDecl();
2499 return;
2500 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002501 // c99 6.2.2 P4.
2502 // For an identifier declared with the storage-class specifier extern in a
2503 // scope in which a prior declaration of that identifier is visible, if
2504 // the prior declaration specifies internal or external linkage, the linkage
2505 // of the identifier at the later declaration is the same as the linkage
2506 // specified at the prior declaration.
2507 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002508 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002509 Old->getLinkage() == InternalLinkage &&
2510 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002511 New->setStorageClass(Old->getStorageClass());
2512
Douglas Gregor0760fa12009-03-10 23:43:53 +00002513 // Keep a chain of previous declarations.
2514 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002515
2516 // Inherit access appropriately.
2517 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002518}
2519
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002520/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2521/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002522Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002523 DeclSpec &DS) {
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002524 return ParsedFreeStandingDeclSpec(S, AS, DS,
2525 MultiTemplateParamsArg(*this, 0, 0));
2526}
2527
2528/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2529/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2530/// parameters to cope with template friend declarations.
2531Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2532 DeclSpec &DS,
2533 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002534 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002535 TagDecl *Tag = 0;
2536 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2537 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2538 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002539 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002540 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002541
2542 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002543 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002544
John McCall07e91c02009-08-06 02:15:43 +00002545 // Note that the above type specs guarantee that the
2546 // type rep is a Decl, whereas in many of the others
2547 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00002548 if (isa<TagDecl>(TagD))
2549 Tag = cast<TagDecl>(TagD);
2550 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2551 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002552 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002553
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00002554 if (Tag) {
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00002555 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00002556 if (Tag->isInvalidDecl())
2557 return Tag;
2558 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00002559
Nuno Lopese9823fa2009-12-17 11:35:26 +00002560 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2561 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2562 // or incomplete types shall not be restrict-qualified."
2563 if (TypeQuals & DeclSpec::TQ_restrict)
2564 Diag(DS.getRestrictSpecLoc(),
2565 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2566 << DS.getSourceRange();
2567 }
2568
Richard Smitha77a0a62011-08-15 21:04:07 +00002569 if (DS.isConstexprSpecified()) {
2570 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2571 // and definitions of functions and variables.
2572 if (Tag)
2573 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2574 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2575 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2576 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2577 else
2578 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2579 // Don't emit warnings after this error.
2580 return TagD;
2581 }
2582
Douglas Gregor3dad8422009-09-26 06:47:28 +00002583 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002584 // If we're dealing with a decl but not a TagDecl, assume that
2585 // whatever routines created it handled the friendship aspect.
2586 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002587 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002588 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002589 }
John McCallaa017372011-03-22 23:00:04 +00002590
2591 // Track whether we warned about the fact that there aren't any
2592 // declarators.
2593 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002594
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002595 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00002596 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002597 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002598 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002599 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002600 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002601
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002602 Diag(DS.getLocStart(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002603 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002604 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002605 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002606 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002607
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002608 // Check for Microsoft C extension: anonymous struct.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002609 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002610 CurContext->isRecord() &&
2611 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2612 // Handle 2 kinds of anonymous struct:
2613 // struct STRUCT;
2614 // and
2615 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2616 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00002617 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002618 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2619 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002620 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002621 << DS.getSourceRange();
2622 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2623 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002624 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002625
David Blaikiebbafb8a2012-03-11 07:00:24 +00002626 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002627 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2628 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2629 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002630 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002631 Diag(Enum->getLocation(), diag::ext_no_declarators)
2632 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002633 emittedWarning = true;
2634 }
2635
2636 // Skip all the checks below if we have a type error.
2637 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002638
John McCallaa017372011-03-22 23:00:04 +00002639 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002640 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002641 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002642 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2643 Tag && isa<EnumDecl>(Tag)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002644 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002645 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002646 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002647 }
2648
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002649 Diag(DS.getLocStart(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002650 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002651 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002652 }
Mike Stump11289f42009-09-09 15:08:12 +00002653
John McCallaa017372011-03-22 23:00:04 +00002654 // We're going to complain about a bunch of spurious specifiers;
2655 // only do this if we're declaring a tag, because otherwise we
2656 // should be getting diag::ext_no_declarators.
2657 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2658 return TagD;
2659
John McCall4d55f5a2011-03-26 02:09:52 +00002660 // Note that a linkage-specification sets a storage class, but
2661 // 'extern "C" struct foo;' is actually valid and not theoretically
2662 // useless.
John McCallaa017372011-03-22 23:00:04 +00002663 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002664 if (!DS.isExternInLinkageSpec())
2665 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2666 << DeclSpec::getSpecifierName(scs);
2667
John McCallaa017372011-03-22 23:00:04 +00002668 if (DS.isThreadSpecified())
2669 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2670 if (DS.getTypeQualifiers()) {
2671 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2672 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2673 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2674 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2675 // Restrict is covered above.
2676 }
2677 if (DS.isInlineSpecified())
2678 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2679 if (DS.isVirtualSpecified())
2680 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2681 if (DS.isExplicitSpecified())
2682 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2683
Douglas Gregor41866812011-09-12 18:37:38 +00002684 if (DS.isModulePrivateSpecified() &&
2685 Tag && Tag->getDeclContext()->isFunctionOrMethod())
2686 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2687 << Tag->getTagKind()
2688 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2689
Eli Friedmane3217952011-12-17 00:36:09 +00002690 // Warn about ignored type attributes, for example:
2691 // __attribute__((aligned)) struct A;
2692 // Attributes should be placed after tag to apply to type declaration.
2693 if (!DS.getAttributes().empty()) {
2694 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2695 if (TypeSpecType == DeclSpec::TST_class ||
2696 TypeSpecType == DeclSpec::TST_struct ||
2697 TypeSpecType == DeclSpec::TST_union ||
2698 TypeSpecType == DeclSpec::TST_enum) {
2699 AttributeList* attrs = DS.getAttributes().getList();
2700 while (attrs) {
2701 Diag(attrs->getScopeLoc(),
2702 diag::warn_declspec_attribute_ignored)
2703 << attrs->getName()
2704 << (TypeSpecType == DeclSpec::TST_class ? 0 :
2705 TypeSpecType == DeclSpec::TST_struct ? 1 :
2706 TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2707 attrs = attrs->getNext();
2708 }
2709 }
2710 }
John McCallaa017372011-03-22 23:00:04 +00002711
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00002712 ActOnDocumentableDecl(TagD);
2713
John McCall48871652010-08-21 09:40:31 +00002714 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002715}
2716
John McCallea305ed2009-12-18 10:40:03 +00002717/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002718/// check if there's an existing declaration that can't be overloaded.
2719///
2720/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002721static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2722 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002723 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002724 DeclarationName Name,
2725 SourceLocation NameLoc,
2726 unsigned diagnostic) {
2727 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2728 Sema::ForRedeclaration);
2729 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002730
John McCallea305ed2009-12-18 10:40:03 +00002731 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002732 return false;
2733
2734 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002735 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002736 assert(PrevDecl && "Expected a non-null Decl");
2737
2738 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2739 return false;
John McCall1f82f242009-11-18 22:49:29 +00002740
John McCallea305ed2009-12-18 10:40:03 +00002741 SemaRef.Diag(NameLoc, diagnostic) << Name;
2742 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002743
2744 return true;
2745}
2746
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002747/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2748/// anonymous struct or union AnonRecord into the owning context Owner
2749/// and scope S. This routine will be invoked just after we realize
2750/// that an unnamed union or struct is actually an anonymous union or
2751/// struct, e.g.,
2752///
2753/// @code
2754/// union {
2755/// int i;
2756/// float f;
2757/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2758/// // f into the surrounding scope.x
2759/// @endcode
2760///
2761/// This routine is recursive, injecting the names of nested anonymous
2762/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002763static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2764 DeclContext *Owner,
2765 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002766 AccessSpecifier AS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002767 SmallVector<NamedDecl*, 2> &Chaining,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002768 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002769 unsigned diagKind
2770 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2771 : diag::err_anonymous_struct_member_redecl;
2772
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002773 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002774
2775 // Look every FieldDecl and IndirectFieldDecl with a name.
2776 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2777 DEnd = AnonRecord->decls_end();
2778 D != DEnd; ++D) {
2779 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2780 cast<NamedDecl>(*D)->getDeclName()) {
2781 ValueDecl *VD = cast<ValueDecl>(*D);
2782 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2783 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002784 // C++ [class.union]p2:
2785 // The names of the members of an anonymous union shall be
2786 // distinct from the names of any other entity in the
2787 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002788 Invalid = true;
2789 } else {
2790 // C++ [class.union]p2:
2791 // For the purpose of name lookup, after the anonymous union
2792 // definition, the members of the anonymous union are
2793 // considered to have been defined in the scope in which the
2794 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002795 unsigned OldChainingSize = Chaining.size();
2796 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2797 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2798 PE = IF->chain_end(); PI != PE; ++PI)
2799 Chaining.push_back(*PI);
2800 else
2801 Chaining.push_back(VD);
2802
Francois Pichet783dd6e2010-11-21 06:08:52 +00002803 assert(Chaining.size() >= 2);
2804 NamedDecl **NamedChain =
2805 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2806 for (unsigned i = 0; i < Chaining.size(); i++)
2807 NamedChain[i] = Chaining[i];
2808
2809 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002810 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2811 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002812 NamedChain, Chaining.size());
2813
2814 IndirectField->setAccess(AS);
2815 IndirectField->setImplicit();
2816 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002817
2818 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002819 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002820
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002821 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002822 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002823 }
2824 }
2825
2826 return Invalid;
2827}
2828
Douglas Gregorc4df4072010-04-19 22:54:31 +00002829/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2830/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002831/// illegal input values are mapped to SC_None.
2832static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002833StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002834 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002835 case DeclSpec::SCS_unspecified: return SC_None;
2836 case DeclSpec::SCS_extern: return SC_Extern;
2837 case DeclSpec::SCS_static: return SC_Static;
2838 case DeclSpec::SCS_auto: return SC_Auto;
2839 case DeclSpec::SCS_register: return SC_Register;
2840 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002841 // Illegal SCSs map to None: error reporting is up to the caller.
2842 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002843 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002844 }
2845 llvm_unreachable("unknown storage class specifier");
2846}
2847
2848/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002849/// a StorageClass. Any error reporting is up to the caller:
2850/// illegal input values are mapped to SC_None.
2851static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002852StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002853 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002854 case DeclSpec::SCS_unspecified: return SC_None;
2855 case DeclSpec::SCS_extern: return SC_Extern;
2856 case DeclSpec::SCS_static: return SC_Static;
2857 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002858 // Illegal SCSs map to None: error reporting is up to the caller.
2859 case DeclSpec::SCS_auto: // Fall through.
2860 case DeclSpec::SCS_mutable: // Fall through.
2861 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002862 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002863 }
2864 llvm_unreachable("unknown storage class specifier");
2865}
2866
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002867/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002868/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002869/// (C++ [class.union]) and a C11 feature; anonymous structures
2870/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002871Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2872 AccessSpecifier AS,
2873 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002874 DeclContext *Owner = Record->getDeclContext();
2875
2876 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002877 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002878 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002879 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002880 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002881 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00002882 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002883
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002884 // C and C++ require different kinds of checks for anonymous
2885 // structs/unions.
2886 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002887 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002888 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002889 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00002890 if (Record->isUnion()) {
2891 // C++ [class.union]p6:
2892 // Anonymous unions declared in a named namespace or in the
2893 // global namespace shall be declared static.
2894 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2895 (isa<TranslationUnitDecl>(Owner) ||
2896 (isa<NamespaceDecl>(Owner) &&
2897 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00002898 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2899 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00002900
2901 // Recover by adding 'static'.
2902 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2903 PrevSpec, DiagID);
2904 }
2905 // C++ [class.union]p6:
2906 // A storage class is not allowed in a declaration of an
2907 // anonymous union in a class scope.
2908 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2909 isa<RecordDecl>(Owner)) {
2910 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00002911 diag::err_anonymous_union_with_storage_spec)
2912 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00002913
2914 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00002915 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
2916 SourceLocation(),
David Blaikie0a8e8992011-10-19 22:43:29 +00002917 PrevSpec, DiagID);
2918 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002919 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002920
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002921 // Ignore const/volatile/restrict qualifiers.
2922 if (DS.getTypeQualifiers()) {
2923 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2924 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2925 << Record->isUnion() << 0
2926 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2927 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
David Blaikie30d15442011-10-19 22:56:21 +00002928 Diag(DS.getVolatileSpecLoc(),
2929 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002930 << Record->isUnion() << 1
2931 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2932 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
David Blaikie30d15442011-10-19 22:56:21 +00002933 Diag(DS.getRestrictSpecLoc(),
2934 diag::ext_anonymous_struct_union_qualified)
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002935 << Record->isUnion() << 2
2936 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2937
2938 DS.ClearTypeQualifiers();
2939 }
2940
Mike Stump11289f42009-09-09 15:08:12 +00002941 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002942 // The member-specification of an anonymous union shall only
2943 // define non-static data members. [Note: nested types and
2944 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002945 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2946 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002947 Mem != MemEnd; ++Mem) {
2948 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2949 // C++ [class.union]p3:
2950 // An anonymous union shall not have private or protected
2951 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002952 assert(FD->getAccess() != AS_none);
2953 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002954 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2955 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2956 Invalid = true;
2957 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002958
Alexis Hunt97ab5542011-05-16 22:41:40 +00002959 // C++ [class.union]p1
2960 // An object of a class with a non-trivial constructor, a non-trivial
2961 // copy constructor, a non-trivial destructor, or a non-trivial copy
2962 // assignment operator cannot be a member of a union, nor can an
2963 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00002964 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002965 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002966 } else if ((*Mem)->isImplicit()) {
2967 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002968 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2969 // This is a type that showed up in an
2970 // elaborated-type-specifier inside the anonymous struct or
2971 // union, but which actually declares a type outside of the
2972 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002973 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2974 if (!MemRecord->isAnonymousStructOrUnion() &&
2975 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002976 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002977 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00002978 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2979 << (int)Record->isUnion();
2980 else {
2981 // This is a nested type declaration.
2982 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2983 << (int)Record->isUnion();
2984 Invalid = true;
2985 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002986 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002987 } else if (isa<AccessSpecDecl>(*Mem)) {
2988 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002989 } else {
2990 // We have something that isn't a non-static data
2991 // member. Complain about it.
2992 unsigned DK = diag::err_anonymous_record_bad_member;
2993 if (isa<TypeDecl>(*Mem))
2994 DK = diag::err_anonymous_record_with_type;
2995 else if (isa<FunctionDecl>(*Mem))
2996 DK = diag::err_anonymous_record_with_function;
2997 else if (isa<VarDecl>(*Mem))
2998 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002999
3000 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003001 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003002 DK == diag::err_anonymous_record_with_type)
3003 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003004 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003005 else {
3006 Diag((*Mem)->getLocation(), DK)
3007 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003008 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003009 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003010 }
3011 }
Mike Stump11289f42009-09-09 15:08:12 +00003012 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003013
3014 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003015 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003016 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003017 Invalid = true;
3018 }
3019
John McCallfa2d6922009-10-22 23:31:08 +00003020 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003021 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003022 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003023 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003024
Mike Stump11289f42009-09-09 15:08:12 +00003025 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003026 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003027 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003028 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003029 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003030 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003031 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003032 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003033 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003034 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003035 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003036 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003037 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003038 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003039 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003040 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3041 assert(SCSpec != DeclSpec::SCS_typedef &&
3042 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003043 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003044 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003045 // mutable can only appear on non-static class members, so it's always
3046 // an error here
3047 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3048 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003049 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003050 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003051 SCSpec = DS.getStorageClassSpecAsWritten();
3052 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003053 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003054
Abramo Bagnaradff19302011-03-08 08:55:46 +00003055 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003056 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003057 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003058 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003059 TInfo, SC, SCAsWritten);
Richard Smith40372352011-09-18 00:06:34 +00003060
3061 // Default-initialize the implicit variable. This initialization will be
3062 // trivial in almost all cases, except if a union member has an in-class
3063 // initializer:
3064 // union { int n = 0; };
3065 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003066 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003067 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003068
3069 // Add the anonymous struct/union object to the current
3070 // context. We'll be referencing this object when we refer to one of
3071 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00003073
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003074 // Inject the members of the anonymous struct/union into the owning
3075 // context and into the identifier resolver chain for name lookup
3076 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003077 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003078 Chain.push_back(Anon);
3079
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003080 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3081 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003082 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003083
3084 // Mark this as an anonymous struct/union type. Note that we do not
3085 // do this until after we have already checked and injected the
3086 // members of this anonymous struct/union type, because otherwise
3087 // the members could be injected twice: once by DeclContext when it
3088 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00003089 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003090 Record->setAnonymousStructOrUnion(true);
3091
3092 if (Invalid)
3093 Anon->setInvalidDecl();
3094
John McCall48871652010-08-21 09:40:31 +00003095 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003096}
3097
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003098/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3099/// Microsoft C anonymous structure.
3100/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3101/// Example:
3102///
3103/// struct A { int a; };
3104/// struct B { struct A; int b; };
3105///
3106/// void foo() {
3107/// B var;
3108/// var.a = 3;
3109/// }
3110///
3111Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3112 RecordDecl *Record) {
3113
3114 // If there is no Record, get the record via the typedef.
3115 if (!Record)
3116 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3117
3118 // Mock up a declarator.
3119 Declarator Dc(DS, Declarator::TypeNameContext);
3120 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3121 assert(TInfo && "couldn't build declarator info for anonymous struct");
3122
3123 // Create a declaration for this anonymous struct.
3124 NamedDecl* Anon = FieldDecl::Create(Context,
3125 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003126 DS.getLocStart(),
3127 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003128 /*IdentifierInfo=*/0,
3129 Context.getTypeDeclType(Record),
3130 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003131 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003132 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003133 Anon->setImplicit();
3134
3135 // Add the anonymous struct object to the current context.
3136 CurContext->addDecl(Anon);
3137
3138 // Inject the members of the anonymous struct into the current
3139 // context and into the identifier resolver chain for name lookup
3140 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003141 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003142 Chain.push_back(Anon);
3143
Nico Weberf8bb3de2012-02-01 00:41:00 +00003144 RecordDecl *RecordDef = Record->getDefinition();
3145 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3146 RecordDef, AS_none,
3147 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003148 Anon->setInvalidDecl();
3149
3150 return Anon;
3151}
Steve Naroff2fea1392007-09-02 02:04:30 +00003152
Douglas Gregor92751d42008-11-17 22:58:34 +00003153/// GetNameForDeclarator - Determine the full declaration name for the
3154/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003155DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003156 return GetNameFromUnqualifiedId(D.getName());
3157}
3158
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003159/// \brief Retrieves the declaration name from a parsed unqualified-id.
3160DeclarationNameInfo
3161Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3162 DeclarationNameInfo NameInfo;
3163 NameInfo.setLoc(Name.StartLocation);
3164
Douglas Gregor7861a802009-11-03 01:35:08 +00003165 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003166
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003167 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003168 case UnqualifiedId::IK_Identifier:
3169 NameInfo.setName(Name.Identifier);
3170 NameInfo.setLoc(Name.StartLocation);
3171 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003172
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003173 case UnqualifiedId::IK_OperatorFunctionId:
3174 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3175 Name.OperatorFunctionId.Operator));
3176 NameInfo.setLoc(Name.StartLocation);
3177 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3178 = Name.OperatorFunctionId.SymbolLocations[0];
3179 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3180 = Name.EndLocation.getRawEncoding();
3181 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003182
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003183 case UnqualifiedId::IK_LiteralOperatorId:
3184 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3185 Name.Identifier));
3186 NameInfo.setLoc(Name.StartLocation);
3187 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3188 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003189
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003190 case UnqualifiedId::IK_ConversionFunctionId: {
3191 TypeSourceInfo *TInfo;
3192 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3193 if (Ty.isNull())
3194 return DeclarationNameInfo();
3195 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3196 Context.getCanonicalType(Ty)));
3197 NameInfo.setLoc(Name.StartLocation);
3198 NameInfo.setNamedTypeInfo(TInfo);
3199 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003200 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003201
3202 case UnqualifiedId::IK_ConstructorName: {
3203 TypeSourceInfo *TInfo;
3204 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3205 if (Ty.isNull())
3206 return DeclarationNameInfo();
3207 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3208 Context.getCanonicalType(Ty)));
3209 NameInfo.setLoc(Name.StartLocation);
3210 NameInfo.setNamedTypeInfo(TInfo);
3211 return NameInfo;
3212 }
3213
3214 case UnqualifiedId::IK_ConstructorTemplateId: {
3215 // In well-formed code, we can only have a constructor
3216 // template-id that refers to the current context, so go there
3217 // to find the actual type being constructed.
3218 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3219 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3220 return DeclarationNameInfo();
3221
3222 // Determine the type of the class being constructed.
3223 QualType CurClassType = Context.getTypeDeclType(CurClass);
3224
3225 // FIXME: Check two things: that the template-id names the same type as
3226 // CurClassType, and that the template-id does not occur when the name
3227 // was qualified.
3228
3229 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3230 Context.getCanonicalType(CurClassType)));
3231 NameInfo.setLoc(Name.StartLocation);
3232 // FIXME: should we retrieve TypeSourceInfo?
3233 NameInfo.setNamedTypeInfo(0);
3234 return NameInfo;
3235 }
3236
3237 case UnqualifiedId::IK_DestructorName: {
3238 TypeSourceInfo *TInfo;
3239 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3240 if (Ty.isNull())
3241 return DeclarationNameInfo();
3242 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3243 Context.getCanonicalType(Ty)));
3244 NameInfo.setLoc(Name.StartLocation);
3245 NameInfo.setNamedTypeInfo(TInfo);
3246 return NameInfo;
3247 }
3248
3249 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003250 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003251 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3252 return Context.getNameForTemplate(TName, TNameLoc);
3253 }
3254
3255 } // switch (Name.getKind())
3256
David Blaikie83d382b2011-09-23 05:06:16 +00003257 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003258}
3259
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003260static QualType getCoreType(QualType Ty) {
3261 do {
3262 if (Ty->isPointerType() || Ty->isReferenceType())
3263 Ty = Ty->getPointeeType();
3264 else if (Ty->isArrayType())
3265 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3266 else
3267 return Ty.withoutLocalFastQualifiers();
3268 } while (true);
3269}
3270
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003271/// hasSimilarParameters - Determine whether the C++ functions Declaration
3272/// and Definition have "nearly" matching parameters. This heuristic is
3273/// used to improve diagnostics in the case where an out-of-line function
3274/// definition doesn't match any declaration within the class or namespace.
3275/// Also sets Params to the list of indices to the parameters that differ
3276/// between the declaration and the definition. If hasSimilarParameters
3277/// returns true and Params is empty, then all of the parameters match.
3278static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003279 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003280 FunctionDecl *Definition,
3281 llvm::SmallVectorImpl<unsigned> &Params) {
3282 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003283 if (Declaration->param_size() != Definition->param_size())
3284 return false;
3285 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3286 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3287 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3288
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003289 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003290 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003291 continue;
3292
3293 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3294 QualType DefParamBaseTy = getCoreType(DefParamTy);
3295 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3296 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3297
3298 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3299 (DeclTyName && DeclTyName == DefTyName))
3300 Params.push_back(Idx);
3301 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00003302 return false;
3303 }
3304
3305 return true;
3306}
3307
John McCall99b2fe52010-04-29 23:50:39 +00003308/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3309/// declarator needs to be rebuilt in the current instantiation.
3310/// Any bits of declarator which appear before the name are valid for
3311/// consideration here. That's specifically the type in the decl spec
3312/// and the base type in any member-pointer chunks.
3313static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3314 DeclarationName Name) {
3315 // The types we specifically need to rebuild are:
3316 // - typenames, typeofs, and decltypes
3317 // - types which will become injected class names
3318 // Of course, we also need to rebuild any type referencing such a
3319 // type. It's safest to just say "dependent", but we call out a
3320 // few cases here.
3321
3322 DeclSpec &DS = D.getMutableDeclSpec();
3323 switch (DS.getTypeSpecType()) {
3324 case DeclSpec::TST_typename:
3325 case DeclSpec::TST_typeofType:
Alexis Hunt4a257072011-05-19 05:37:45 +00003326 case DeclSpec::TST_decltype:
Eli Friedman0dfb8892011-10-06 23:00:33 +00003327 case DeclSpec::TST_underlyingType:
3328 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00003329 // Grab the type from the parser.
3330 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00003331 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00003332 if (T.isNull() || !T->isDependentType()) break;
3333
3334 // Make sure there's a type source info. This isn't really much
3335 // of a waste; most dependent types should have type source info
3336 // attached already.
3337 if (!TSI)
3338 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3339
3340 // Rebuild the type in the current instantiation.
3341 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3342 if (!TSI) return true;
3343
3344 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00003345 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3346 DS.UpdateTypeRep(LocType);
3347 break;
3348 }
3349
3350 case DeclSpec::TST_typeofExpr: {
3351 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00003352 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00003353 if (Result.isInvalid()) return true;
3354 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00003355 break;
3356 }
3357
3358 default:
3359 // Nothing to do for these decl specs.
3360 break;
3361 }
3362
3363 // It doesn't matter what order we do this in.
3364 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3365 DeclaratorChunk &Chunk = D.getTypeObject(I);
3366
3367 // The only type information in the declarator which can come
3368 // before the declaration name is the base type of a member
3369 // pointer.
3370 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3371 continue;
3372
3373 // Rebuild the scope specifier in-place.
3374 CXXScopeSpec &SS = Chunk.Mem.Scope();
3375 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3376 return true;
3377 }
3378
3379 return false;
3380}
3381
Anders Carlsson1052fd72011-07-04 16:28:17 +00003382Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00003383 D.setFunctionDefinitionKind(FDK_Declaration);
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003384 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3385
3386 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00003387 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003388 Dcl->setTopLevelDeclInObjCContainer();
3389
3390 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00003391}
3392
Richard Smithdda56e42011-04-15 14:24:37 +00003393/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3394/// If T is the name of a class, then each of the following shall have a
3395/// name different from T:
3396/// - every static data member of class T;
3397/// - every member function of class T
3398/// - every member of class T that is itself a type;
3399/// \returns true if the declaration name violates these rules.
3400bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3401 DeclarationNameInfo NameInfo) {
3402 DeclarationName Name = NameInfo.getName();
3403
3404 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3405 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3406 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3407 return true;
3408 }
3409
3410 return false;
3411}
Douglas Gregor31feb332012-03-17 23:06:31 +00003412
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003413/// \brief Diagnose a declaration whose declarator-id has the given
3414/// nested-name-specifier.
3415///
3416/// \param SS The nested-name-specifier of the declarator-id.
3417///
3418/// \param DC The declaration context to which the nested-name-specifier
3419/// resolves.
3420///
3421/// \param Name The name of the entity being declared.
3422///
3423/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00003424///
3425/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003426bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00003427 DeclarationName Name,
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003428 SourceLocation Loc) {
3429 DeclContext *Cur = CurContext;
3430 while (isa<LinkageSpecDecl>(Cur))
3431 Cur = Cur->getParent();
3432
3433 // C++ [dcl.meaning]p1:
3434 // A declarator-id shall not be qualified except for the definition
3435 // of a member function (9.3) or static data member (9.4) outside of
3436 // its class, the definition or explicit instantiation of a function
3437 // or variable member of a namespace outside of its namespace, or the
3438 // definition of an explicit specialization outside of its namespace,
3439 // or the declaration of a friend function that is a member of
3440 // another class or namespace (11.3). [...]
3441
3442 // The user provided a superfluous scope specifier that refers back to the
3443 // class or namespaces in which the entity is already declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00003444 //
3445 // class X {
3446 // void X::f();
3447 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003448 if (Cur->Equals(DC)) {
Douglas Gregor31feb332012-03-17 23:06:31 +00003449 Diag(Loc, diag::warn_member_extra_qualification)
3450 << Name << FixItHint::CreateRemoval(SS.getRange());
3451 SS.clear();
3452 return false;
3453 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003454
3455 // Check whether the qualifying scope encloses the scope of the original
3456 // declaration.
3457 if (!Cur->Encloses(DC)) {
3458 if (Cur->isRecord())
3459 Diag(Loc, diag::err_member_qualification)
3460 << Name << SS.getRange();
3461 else if (isa<TranslationUnitDecl>(DC))
3462 Diag(Loc, diag::err_invalid_declarator_global_scope)
3463 << Name << SS.getRange();
3464 else if (isa<FunctionDecl>(Cur))
3465 Diag(Loc, diag::err_invalid_declarator_in_function)
3466 << Name << SS.getRange();
3467 else
3468 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00003469 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003470
Douglas Gregor31feb332012-03-17 23:06:31 +00003471 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003472 }
3473
3474 if (Cur->isRecord()) {
3475 // Cannot qualify members within a class.
3476 Diag(Loc, diag::err_member_qualification)
3477 << Name << SS.getRange();
3478 SS.clear();
3479
3480 // C++ constructors and destructors with incorrect scopes can break
3481 // our AST invariants by having the wrong underlying types. If
3482 // that's the case, then drop this declaration entirely.
3483 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3484 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3485 !Context.hasSameType(Name.getCXXNameType(),
3486 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3487 return true;
3488
3489 return false;
3490 }
Douglas Gregor31feb332012-03-17 23:06:31 +00003491
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003492 // C++11 [dcl.meaning]p1:
3493 // [...] "The nested-name-specifier of the qualified declarator-id shall
3494 // not begin with a decltype-specifer"
3495 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3496 while (SpecLoc.getPrefix())
3497 SpecLoc = SpecLoc.getPrefix();
3498 if (dyn_cast_or_null<DecltypeType>(
3499 SpecLoc.getNestedNameSpecifier()->getAsType()))
3500 Diag(Loc, diag::err_decltype_in_declarator)
3501 << SpecLoc.getTypeLoc().getSourceRange();
3502
Douglas Gregor31feb332012-03-17 23:06:31 +00003503 return false;
3504}
3505
John McCall48871652010-08-21 09:40:31 +00003506Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003507 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003508 // TODO: consider using NameInfo for diagnostic.
3509 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3510 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00003511
Chris Lattner02c04392007-07-25 00:24:17 +00003512 // All of these full declarators require an identifier. If it doesn't have
3513 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00003514 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003515 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003516 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003517 diag::err_declarator_need_ident)
3518 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00003519 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00003520 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3521 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003522
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003523 // The scope passed in may not be a decl scope. Zip up the scope tree until
3524 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00003525 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003526 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003527 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003528
John McCall99b2fe52010-04-29 23:50:39 +00003529 DeclContext *DC = CurContext;
3530 if (D.getCXXScopeSpec().isInvalid())
3531 D.setInvalidType();
3532 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003533 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3534 UPPC_DeclarationQualifier))
3535 return 0;
3536
John McCall99b2fe52010-04-29 23:50:39 +00003537 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3538 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3539 if (!DC) {
3540 // If we could not compute the declaration context, it's because the
3541 // declaration context is dependent but does not refer to a class,
3542 // class template, or class template partial specialization. Complain
3543 // and return early, to avoid the coming semantic disaster.
3544 Diag(D.getIdentifierLoc(),
3545 diag::err_template_qualified_declarator_no_match)
3546 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3547 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003548 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003549 }
John McCall99b2fe52010-04-29 23:50:39 +00003550 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003551
John McCall99b2fe52010-04-29 23:50:39 +00003552 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003553 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003554 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003555
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003556 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3557 Diag(D.getIdentifierLoc(),
3558 diag::err_member_def_undefined_record)
3559 << Name << DC << D.getCXXScopeSpec().getRange();
3560 D.setInvalidType();
3561 } else if (!D.getDeclSpec().isFriendSpecified()) {
3562 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3563 Name, D.getIdentifierLoc())) {
3564 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00003565 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003566
3567 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00003568 }
John McCall99b2fe52010-04-29 23:50:39 +00003569 }
3570
3571 // Check whether we need to rebuild the type of the given
3572 // declaration in the current instantiation.
3573 if (EnteringContext && IsDependentContext &&
3574 TemplateParamLists.size() != 0) {
3575 ContextRAII SavedContext(*this, DC);
3576 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3577 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003578 }
3579 }
Richard Smithdda56e42011-04-15 14:24:37 +00003580
3581 if (DiagnoseClassNameShadow(DC, NameInfo))
3582 // If this is a typedef, we'll end up spewing multiple diagnostics.
3583 // Just return early; it's safer.
3584 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3585 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003586
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003587 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003588
John McCall8cb7bdf2010-06-04 23:28:52 +00003589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3590 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003591
Douglas Gregor506bd562010-12-13 22:49:22 +00003592 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3593 UPPC_DeclarationType))
3594 D.setInvalidType();
3595
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003596 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003597 ForRedeclaration);
3598
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003599 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003600 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003601 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003602
3603 // If the declaration we're planning to build will be a function
3604 // or object with linkage, then look for another declaration with
3605 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3606 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3607 /* Do nothing*/;
3608 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003609 if (CurContext->isFunctionOrMethod() ||
3610 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003611 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003612 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003613 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003614 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003615 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003616 IsLinkageLookup = true;
3617
3618 if (IsLinkageLookup)
3619 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003620
John McCall1f82f242009-11-18 22:49:29 +00003621 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003622 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003623 LookupQualifiedName(Previous, DC);
3624
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003625 // C++ [dcl.meaning]p1:
3626 // When the declarator-id is qualified, the declaration shall refer to a
3627 // previously declared member of the class or namespace to which the
3628 // qualifier refers (or, in the case of a namespace, of an element of the
3629 // inline namespace set of that namespace (7.3.1)) or to a specialization
3630 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003631 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003632 // Note that we already checked the context above, and that we do not have
3633 // enough information to make sure that Previous contains the declaration
3634 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00003635 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003636 // class X {
3637 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003638 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003639 // };
3640 //
Douglas Gregorad590502008-12-15 23:53:10 +00003641 // void X::f(int) { } // ill-formed
3642 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003643 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00003644 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003645 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003646
3647 // C++ [dcl.meaning]p1:
3648 // [...] the member shall not merely have been introduced by a
3649 // using-declaration in the scope of the class or namespace nominated by
3650 // the nested-name-specifier of the declarator-id.
3651 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003652 }
3653
John McCall1f82f242009-11-18 22:49:29 +00003654 if (Previous.isSingleResult() &&
3655 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003656 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003657 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00003658 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3659 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003660
Douglas Gregor5101c242008-12-05 18:15:24 +00003661 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003662 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003663 }
3664
Douglas Gregor83a586e2008-04-13 21:07:44 +00003665 // In C++, the previous declaration we find might be a tag type
3666 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003667 // tag type. Note that this does does not apply if we're declaring a
3668 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003669 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003670 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003671 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003672
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003673 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00003674 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003675 if (TemplateParamLists.size()) {
3676 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003677 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003678 }
Mike Stump11289f42009-09-09 15:08:12 +00003679
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003680 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003681 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003682 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003683 move(TemplateParamLists),
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003684 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00003685 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003686 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3687 move(TemplateParamLists));
Chris Lattner01a7c532007-01-25 23:09:03 +00003688 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003689
3690 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003691 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003693 // If this has an identifier and is not an invalid redeclaration or
3694 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003695 if (New->getDeclName() && AddToScope &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003696 !(D.isRedeclaration() && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003697 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003698
John McCall48871652010-08-21 09:40:31 +00003699 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003700}
3701
Eli Friedmana3b1d032009-02-21 00:44:51 +00003702/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3703/// types into constant array types in certain situations which would otherwise
3704/// be errors (for GCC compatibility).
3705static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3706 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003707 bool &SizeIsNegative,
3708 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003709 // This method tries to turn a variable array into a constant
3710 // array even when the size isn't an ICE. This is necessary
3711 // for compatibility with code that depends on gcc's buggy
3712 // constant expression folding, like struct {char x[(int)(char*)2];}
3713 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003714 Oversized = 0;
3715
3716 if (T->isDependentType())
3717 return QualType();
3718
John McCall8ccfcb52009-09-24 19:53:00 +00003719 QualifierCollector Qs;
3720 const Type *Ty = Qs.strip(T);
3721
3722 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003723 QualType Pointee = PTy->getPointeeType();
3724 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003725 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3726 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003727 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003728 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003729 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003730 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003731 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3732 QualType Inner = PTy->getInnerType();
3733 QualType FixedType =
3734 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3735 Oversized);
3736 if (FixedType.isNull()) return FixedType;
3737 FixedType = Context.getParenType(FixedType);
3738 return Qs.apply(Context, FixedType);
3739 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003740
3741 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003742 if (!VLATy)
3743 return QualType();
3744 // FIXME: We should probably handle this case
3745 if (VLATy->getElementType()->isVariablyModifiedType())
3746 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003747
Richard Smith42d3af92011-12-07 00:43:50 +00003748 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003749 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00003750 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00003751 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003752
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003753 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003754 if (Res.isSigned() && Res.isNegative()) {
3755 SizeIsNegative = true;
3756 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003757 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003758
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003759 // Check whether the array is too large to be addressed.
3760 unsigned ActiveSizeBits
3761 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3762 Res);
3763 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3764 Oversized = Res;
3765 return QualType();
3766 }
3767
3768 return Context.getConstantArrayType(VLATy->getElementType(),
3769 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003770}
3771
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003772/// \brief Register the given locally-scoped external C declaration so
3773/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003774void
John McCall1f82f242009-11-18 22:49:29 +00003775Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3776 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003777 Scope *S) {
3778 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3779 "Decl is not a locally-scoped decl!");
3780 // Note that we have a locally-scoped external with this name.
3781 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3782
John McCall1f82f242009-11-18 22:49:29 +00003783 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003784 return;
3785
John McCall1f82f242009-11-18 22:49:29 +00003786 NamedDecl *PrevDecl = Previous.getFoundDecl();
3787
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003788 // If there was a previous declaration of this variable, it may be
3789 // in our identifier chain. Update the identifier chain with the new
3790 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003791 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003792 // The previous declaration was found on the identifer resolver
3793 // chain, so remove it from its scope.
Douglas Gregor825faf72011-06-29 21:22:02 +00003794
3795 if (S->isDeclScope(PrevDecl)) {
3796 // Special case for redeclarations in the SAME scope.
3797 // Because this declaration is going to be added to the identifier chain
3798 // later, we should temporarily take it OFF the chain.
3799 IdResolver.RemoveDecl(ND);
3800
3801 } else {
3802 // Find the scope for the original declaration.
3803 while (S && !S->isDeclScope(PrevDecl))
3804 S = S->getParent();
3805 }
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003806
3807 if (S)
John McCall48871652010-08-21 09:40:31 +00003808 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003809 }
3810}
3811
Douglas Gregordc5c9582011-07-28 14:20:37 +00003812llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3813Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3814 if (ExternalSource) {
3815 // Load locally-scoped external decls from the external source.
3816 SmallVector<NamedDecl *, 4> Decls;
3817 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3818 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3819 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3820 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3821 if (Pos == LocallyScopedExternalDecls.end())
3822 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3823 }
3824 }
3825
3826 return LocallyScopedExternalDecls.find(Name);
3827}
3828
Eli Friedman574c7452009-04-07 19:37:57 +00003829/// \brief Diagnose function specifiers on a declaration of an identifier that
3830/// does not identify a function.
3831void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3832 // FIXME: We should probably indicate the identifier in question to avoid
3833 // confusion for constructs like "inline int a(), b;"
3834 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003835 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003836 diag::err_inline_non_function);
3837
3838 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003839 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003840 diag::err_virtual_non_function);
3841
3842 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003843 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003844 diag::err_explicit_non_function);
3845}
3846
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003847NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003848Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003849 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003850 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3851 if (D.getCXXScopeSpec().isSet()) {
3852 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3853 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003854 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003855 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00003856 DC = CurContext;
3857 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003858 }
3859
David Blaikiebbafb8a2012-03-11 07:00:24 +00003860 if (getLangOpts().CPlusPlus) {
Douglas Gregor0c880302009-03-11 23:00:04 +00003861 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003862 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003863 }
3864
Eli Friedman574c7452009-04-07 19:37:57 +00003865 DiagnoseFunctionSpecifiers(D);
3866
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003867 if (D.getDeclSpec().isThreadSpecified())
3868 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00003869 if (D.getDeclSpec().isConstexprSpecified())
3870 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3871 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003872
Douglas Gregord8f446f2010-07-13 06:37:01 +00003873 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3874 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3875 << D.getName().getSourceRange();
3876 return 0;
3877 }
3878
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003879 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003880 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003881
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003882 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003883 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00003884
Richard Smith3f1b5d02011-05-05 21:57:07 +00003885 CheckTypedefForVariablyModifiedType(S, NewTD);
3886
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00003887 bool Redeclaration = D.isRedeclaration();
3888 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3889 D.setRedeclaration(Redeclaration);
3890 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00003891}
3892
Richard Smith3f1b5d02011-05-05 21:57:07 +00003893void
3894Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00003895 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3896 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00003897 // Note that variably modified types must be fixed before merging the decl so
3898 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00003899 QualType T = NewTD->getUnderlyingType();
3900 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00003901 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003902
Chris Lattner9fecd742009-04-19 05:21:20 +00003903 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003904 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003905 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003906 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003907 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3908 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003909 if (!FixedTy.isNull()) {
Richard Smithdda56e42011-04-15 14:24:37 +00003910 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00003911 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00003912 } else {
3913 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00003914 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003915 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00003916 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003917 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00003918 Diag(NewTD->getLocation(), diag::err_array_too_large)
3919 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003920 else
Richard Smithdda56e42011-04-15 14:24:37 +00003921 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003922 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00003923 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003924 }
3925 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003926}
Douglas Gregor27821ce2009-07-07 16:35:42 +00003927
Richard Smith3f1b5d02011-05-05 21:57:07 +00003928
3929/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3930/// declares a typedef-name, either using the 'typedef' type specifier or via
3931/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3932NamedDecl*
3933Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3934 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00003935 // Merge the decl with the existing one if appropriate. If the decl is
3936 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003937 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00003938 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003939 if (!Previous.empty()) {
3940 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00003941 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003942 }
3943
Douglas Gregor27821ce2009-07-07 16:35:42 +00003944 // If this is the C FILE type, notify the AST context.
3945 if (IdentifierInfo *II = NewTD->getIdentifier())
3946 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003947 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00003948 if (II->isStr("FILE"))
3949 Context.setFILEDecl(NewTD);
3950 else if (II->isStr("jmp_buf"))
3951 Context.setjmp_bufDecl(NewTD);
3952 else if (II->isStr("sigjmp_buf"))
3953 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00003954 else if (II->isStr("ucontext_t"))
3955 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00003956 }
3957
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003958 return NewTD;
3959}
3960
Douglas Gregor5d68a202009-02-24 19:23:27 +00003961/// \brief Determines whether the given declaration is an out-of-scope
3962/// previous declaration.
3963///
3964/// This routine should be invoked when name lookup has found a
3965/// previous declaration (PrevDecl) that is not in the scope where a
3966/// new declaration by the same name is being introduced. If the new
3967/// declaration occurs in a local scope, previous declarations with
3968/// linkage may still be considered previous declarations (C99
3969/// 6.2.2p4-5, C++ [basic.link]p6).
3970///
3971/// \param PrevDecl the previous declaration found by name
3972/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00003973///
Douglas Gregor5d68a202009-02-24 19:23:27 +00003974/// \param DC the context in which the new declaration is being
3975/// declared.
3976///
3977/// \returns true if PrevDecl is an out-of-scope previous declaration
3978/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00003979static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00003980isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3981 ASTContext &Context) {
3982 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00003983 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003984
Douglas Gregoreddf4332009-02-24 20:03:32 +00003985 if (!PrevDecl->hasLinkage())
3986 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003987
David Blaikiebbafb8a2012-03-11 07:00:24 +00003988 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00003989 // C++ [basic.link]p6:
3990 // If there is a visible declaration of an entity with linkage
3991 // having the same name and type, ignoring entities declared
3992 // outside the innermost enclosing namespace scope, the block
3993 // scope declaration declares that same entity and receives the
3994 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00003995 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00003996 if (!OuterContext->isFunctionOrMethod())
3997 // This rule only applies to block-scope declarations.
3998 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00003999
4000 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4001 if (PrevOuterContext->isRecord())
4002 // We found a member function: ignore it.
4003 return false;
4004
4005 // Find the innermost enclosing namespace for the new and
4006 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004007 OuterContext = OuterContext->getEnclosingNamespaceContext();
4008 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004009
Douglas Gregorfcee9462010-08-27 22:55:10 +00004010 // The previous declaration is in a different namespace, so it
4011 // isn't the same function.
4012 if (!OuterContext->Equals(PrevOuterContext))
4013 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004014 }
4015
Douglas Gregor5d68a202009-02-24 19:23:27 +00004016 return true;
4017}
4018
John McCall3e11ebe2010-03-15 10:12:16 +00004019static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4020 CXXScopeSpec &SS = D.getCXXScopeSpec();
4021 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004022 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004023}
4024
John McCall31168b02011-06-15 23:02:42 +00004025bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4026 QualType type = decl->getType();
4027 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4028 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4029 // Various kinds of declaration aren't allowed to be __autoreleasing.
4030 unsigned kind = -1U;
4031 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4032 if (var->hasAttr<BlocksAttr>())
4033 kind = 0; // __block
4034 else if (!var->hasLocalStorage())
4035 kind = 1; // global
4036 } else if (isa<ObjCIvarDecl>(decl)) {
4037 kind = 3; // ivar
4038 } else if (isa<FieldDecl>(decl)) {
4039 kind = 2; // field
4040 }
4041
4042 if (kind != -1U) {
4043 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4044 << kind;
4045 }
4046 } else if (lifetime == Qualifiers::OCL_None) {
4047 // Try to infer lifetime.
4048 if (!type->isObjCLifetimeType())
4049 return false;
4050
4051 lifetime = type->getObjCARCImplicitLifetime();
4052 type = Context.getLifetimeQualifiedType(type, lifetime);
4053 decl->setType(type);
4054 }
4055
4056 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4057 // Thread-local variables cannot have lifetime.
4058 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4059 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004060 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004061 << var->getType();
4062 return true;
4063 }
4064 }
4065
4066 return false;
4067}
4068
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004069NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00004070Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004071 TypeSourceInfo *TInfo, LookupResult &Previous,
4072 MultiTemplateParamsArg TemplateParamLists) {
4073 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004074 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004075
4076 // Check that there are no default arguments (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004077 if (getLangOpts().CPlusPlus)
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004078 CheckExtraCXXDefaultArguments(D);
4079
Douglas Gregorc4df4072010-04-19 22:54:31 +00004080 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4081 assert(SCSpec != DeclSpec::SCS_typedef &&
4082 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00004083 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00004084 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004085 // mutable can only appear on non-static class members, so it's always
4086 // an error here
4087 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004088 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004089 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004090 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00004091 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4092 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00004093 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004094
4095 IdentifierInfo *II = Name.getAsIdentifierInfo();
4096 if (!II) {
4097 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00004098 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004099 return 0;
4100 }
4101
Eli Friedman574c7452009-04-07 19:37:57 +00004102 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00004103
Douglas Gregor212cab32009-03-11 20:22:50 +00004104 if (!DC->isRecord() && S->getFnParent() == 0) {
4105 // C99 6.9p2: The storage-class specifiers auto and register shall not
4106 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00004107 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00004108
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004109 // If this is a register variable with an asm label specified, then this
4110 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00004111 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004112 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4113 else
4114 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004115 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004116 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004117 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004118
David Blaikiebbafb8a2012-03-11 07:00:24 +00004119 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004120 // Set up the special work-group-local storage class for variables in the
4121 // OpenCL __local address space.
4122 if (R.getAddressSpace() == LangAS::opencl_local)
4123 SC = SC_OpenCLWorkGroupLocal;
4124 }
4125
Ted Kremenek582a0992011-01-23 17:04:59 +00004126 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004127 VarDecl *NewVD;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004128 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004129 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004130 D.getIdentifierLoc(), II,
4131 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004132
4133 if (D.isInvalidType())
4134 NewVD->setInvalidDecl();
4135 } else {
4136 if (DC->isRecord() && !CurContext->isRecord()) {
4137 // This is an out-of-line definition of a static data member.
4138 if (SC == SC_Static) {
4139 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4140 diag::err_static_out_of_line)
4141 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4142 } else if (SC == SC_None)
4143 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00004144 }
Richard Smith42973752012-02-16 20:41:22 +00004145 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004146 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4147 if (RD->isLocalClass())
4148 Diag(D.getIdentifierLoc(),
4149 diag::err_static_data_member_not_allowed_in_local_class)
4150 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004151
Richard Smith42973752012-02-16 20:41:22 +00004152 // C++98 [class.union]p1: If a union contains a static data member,
4153 // the program is ill-formed. C++11 drops this restriction.
4154 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004155 Diag(D.getIdentifierLoc(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00004156 getLangOpts().CPlusPlus0x
Richard Smith42973752012-02-16 20:41:22 +00004157 ? diag::warn_cxx98_compat_static_data_member_in_union
4158 : diag::ext_static_data_member_in_union) << Name;
4159 // We conservatively disallow static data members in anonymous structs.
4160 else if (!RD->getDeclName())
4161 Diag(D.getIdentifierLoc(),
4162 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004163 << Name << RD->isUnion();
4164 }
4165 }
4166
4167 // Match up the template parameter lists with the scope specifier, then
4168 // determine whether we have a template or a template specialization.
4169 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004170 bool Invalid = false;
4171 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004172 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004173 D.getDeclSpec().getLocStart(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004174 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004175 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00004176 TemplateParamLists.get(),
4177 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00004178 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004179 isExplicitSpecialization,
4180 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004181 if (TemplateParams->size() > 0) {
4182 // There is no such thing as a variable template.
4183 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4184 << II
4185 << SourceRange(TemplateParams->getTemplateLoc(),
4186 TemplateParams->getRAngleLoc());
4187 return 0;
4188 } else {
4189 // There is an extraneous 'template<>' for this variable. Complain
4190 // about it, but allow the declaration of the variable.
4191 Diag(TemplateParams->getTemplateLoc(),
4192 diag::err_template_variable_noparams)
4193 << II
4194 << SourceRange(TemplateParams->getTemplateLoc(),
4195 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004196 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00004197 }
Mike Stump11289f42009-09-09 15:08:12 +00004198
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004199 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004200 D.getIdentifierLoc(), II,
4201 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004202
Richard Smithb2bc2e62011-02-21 20:05:19 +00004203 // If this decl has an auto type in need of deduction, make a note of the
4204 // Decl so we can diagnose uses of it in its own initializer.
4205 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4206 R->getContainedAutoType())
4207 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00004208
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004209 if (D.isInvalidType() || Invalid)
4210 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004211
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004212 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00004213
Abramo Bagnara60804e12011-03-18 15:16:37 +00004214 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004215 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00004216 TemplateParamLists.size(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004217 TemplateParamLists.release());
4218 }
Richard Smitha77a0a62011-08-15 21:04:07 +00004219
Richard Smith6331c402012-02-13 22:16:19 +00004220 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00004221 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004222 }
4223
Douglas Gregor41866812011-09-12 18:37:38 +00004224 // Set the lexical context. If the declarator has a C++ scope specifier, the
4225 // lexical context will be different from the semantic context.
4226 NewVD->setLexicalDeclContext(CurContext);
4227
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004228 if (D.getDeclSpec().isThreadSpecified()) {
4229 if (NewVD->hasLocalStorage())
4230 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Douglas Gregore8bbc122011-09-02 00:18:52 +00004231 else if (!Context.getTargetInfo().isTLSSupported())
Eli Friedmandaea3f62009-04-19 21:48:33 +00004232 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004233 else
4234 NewVD->setThreadSpecified(true);
4235 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004236
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00004237 if (D.getDeclSpec().isModulePrivateSpecified()) {
4238 if (isExplicitSpecialization)
4239 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4240 << 2
4241 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00004242 else if (NewVD->hasLocalStorage())
4243 Diag(NewVD->getLocation(), diag::err_module_private_local)
4244 << 0 << NewVD->getDeclName()
4245 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4246 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00004247 else
4248 NewVD->setModulePrivate();
4249 }
Douglas Gregor26701a42011-09-09 02:06:17 +00004250
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004251 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004252 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004253
John McCall31168b02011-06-15 23:02:42 +00004254 // In auto-retain/release, infer strong retension for variables of
4255 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004256 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00004257 NewVD->setInvalidDecl();
4258
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004259 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00004260 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004261 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004262 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004263 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00004264 if (S->getFnParent() != 0) {
4265 switch (SC) {
4266 case SC_None:
4267 case SC_Auto:
4268 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4269 break;
4270 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00004271 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00004272 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4273 break;
4274 case SC_Static:
4275 case SC_Extern:
4276 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004277 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00004278 break;
4279 }
4280 }
4281
4282 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00004283 Context, Label));
David Chisnall0867d9c2012-02-18 16:12:34 +00004284 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4285 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4286 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4287 if (I != ExtnameUndeclaredIdentifiers.end()) {
4288 NewVD->addAttr(I->second);
4289 ExtnameUndeclaredIdentifiers.erase(I);
4290 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004291 }
4292
John McCalla2a3f7d2010-03-16 21:48:18 +00004293 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00004294 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00004295 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00004296
John McCall1f82f242009-11-18 22:49:29 +00004297 // Don't consider existing declarations that are in a different
4298 // scope and are out-of-semantic-context declarations (if the new
4299 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00004300 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004301 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004302
David Blaikiebbafb8a2012-03-11 07:00:24 +00004303 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004304 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4305 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004306 // Merge the decl with the existing one if appropriate.
4307 if (!Previous.empty()) {
4308 if (Previous.isSingleResult() &&
4309 isa<FieldDecl>(Previous.getFoundDecl()) &&
4310 D.getCXXScopeSpec().isSet()) {
4311 // The user tried to define a non-static data member
4312 // out-of-line (C++ [dcl.meaning]p1).
4313 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4314 << D.getCXXScopeSpec().getRange();
4315 Previous.clear();
4316 NewVD->setInvalidDecl();
4317 }
4318 } else if (D.getCXXScopeSpec().isSet()) {
4319 // No previous declaration in the qualifying scope.
4320 Diag(D.getIdentifierLoc(), diag::err_no_member)
4321 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004322 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004323 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004324 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004325
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004326 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004327
4328 // This is an explicit specialization of a static data member. Check it.
4329 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4330 CheckMemberSpecialization(NewVD, Previous))
4331 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004332 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00004333
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004334 // If this is a locally-scoped extern C variable, update the map of
4335 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00004336 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004337 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004338 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004339
Eli Friedman570024a2010-08-05 06:57:20 +00004340 // If there's a #pragma GCC visibility in scope, and this isn't a class
4341 // member, set the visibility of this variable.
4342 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4343 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004344
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004345 MarkUnusedFileScopedDecl(NewVD);
4346
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004347 return NewVD;
4348}
4349
John McCalldf8b37c2010-03-22 09:20:08 +00004350/// \brief Diagnose variable or built-in function shadowing. Implements
4351/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00004352///
John McCalldf8b37c2010-03-22 09:20:08 +00004353/// This method is called whenever a VarDecl is added to a "useful"
4354/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00004355///
John McCall2d8c7602010-03-20 04:12:52 +00004356/// \param S the scope in which the shadowing name is being declared
4357/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00004358///
John McCalldf8b37c2010-03-22 09:20:08 +00004359void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00004360 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004361 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00004362 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00004363 return;
4364
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00004365 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00004366 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00004367 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00004368
4369 DeclContext *NewDC = D->getDeclContext();
4370
John McCall2d8c7602010-03-20 04:12:52 +00004371 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00004372 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00004373 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00004374
John McCalla2a3f7d2010-03-16 21:48:18 +00004375 NamedDecl* ShadowedDecl = R.getFoundDecl();
4376 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4377 return;
4378
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00004379 // Fields are not shadowed by variables in C++ static methods.
4380 if (isa<FieldDecl>(ShadowedDecl))
4381 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4382 if (MD->isStatic())
4383 return;
4384
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00004385 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4386 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00004387 // For shadowing external vars, make sure that we point to the global
4388 // declaration, not a locally scoped extern declaration.
4389 for (VarDecl::redecl_iterator
4390 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4391 I != E; ++I)
4392 if (I->isFileVarDecl()) {
4393 ShadowedDecl = *I;
4394 break;
4395 }
4396 }
4397
4398 DeclContext *OldDC = ShadowedDecl->getDeclContext();
4399
John McCall2d8c7602010-03-20 04:12:52 +00004400 // Only warn about certain kinds of shadowing for class members.
4401 if (NewDC && NewDC->isRecord()) {
4402 // In particular, don't warn about shadowing non-class members.
4403 if (!OldDC->isRecord())
4404 return;
4405
4406 // TODO: should we warn about static data members shadowing
4407 // static data members from base classes?
4408
4409 // TODO: don't diagnose for inaccessible shadowed members.
4410 // This is hard to do perfectly because we might friend the
4411 // shadowing context, but that's just a false negative.
4412 }
4413
4414 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00004415 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00004416 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00004417 if (isa<FieldDecl>(ShadowedDecl))
4418 Kind = 3; // field
4419 else
4420 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00004421 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00004422 Kind = 1; // global
4423 else
4424 Kind = 0; // local
4425
John McCall2d8c7602010-03-20 04:12:52 +00004426 DeclarationName Name = R.getLookupName();
4427
John McCalla2a3f7d2010-03-16 21:48:18 +00004428 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00004429 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00004430 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4431}
4432
John McCalldf8b37c2010-03-22 09:20:08 +00004433/// \brief Check -Wshadow without the advantage of a previous lookup.
4434void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004435 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00004436 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004437 return;
4438
John McCalldf8b37c2010-03-22 09:20:08 +00004439 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4440 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4441 LookupName(R, S);
4442 CheckShadow(S, D, R);
4443}
4444
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004445/// \brief Perform semantic checking on a newly-created variable
4446/// declaration.
4447///
4448/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004449/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004450/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00004451/// have been translated into a declaration, and to check variables
4452/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004453///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004454/// Sets NewVD->isInvalidDecl() if an error was encountered.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004455///
4456/// Returns true if the variable declaration is a redeclaration.
4457bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4458 LookupResult &Previous) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004459 // If the decl is already known invalid, don't check it.
4460 if (NewVD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004461 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004462
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004463 QualType T = NewVD->getType();
4464
John McCall8b07ec22010-05-15 11:32:37 +00004465 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00004466 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4467 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00004468 T = Context.getObjCObjectPointerType(T);
4469 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004472 // Emit an error if an address space was applied to decl with local storage.
4473 // This includes arrays of objects with address space qualifiers, but not
4474 // automatic variables that point to other address spaces.
4475 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00004476 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004477 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004478 NewVD->setInvalidDecl();
4479 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004480 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00004481
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00004482 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
4483 // scope.
4484 if ((getLangOpts().OpenCLVersion >= 120)
4485 && NewVD->isStaticLocal()) {
4486 Diag(NewVD->getLocation(), diag::err_static_function_scope);
4487 NewVD->setInvalidDecl();
4488 return false;
4489 }
4490
Mike Stumpca5ae662009-04-14 00:57:29 +00004491 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004492 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004493 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00004494 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4495 else
4496 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4497 }
Chris Lattner88fdea82010-10-10 18:16:20 +00004498
Chris Lattner9fecd742009-04-19 05:21:20 +00004499 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00004500 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00004501 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00004502 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004503
Chris Lattner9fecd742009-04-19 05:21:20 +00004504 if ((isVM && NewVD->hasLinkage()) ||
4505 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004506 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004507 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00004508 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004509 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4510 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00004511
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004512 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004513 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00004514 // FIXME: This won't give the correct result for
4515 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00004516 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004517
Anders Carlsson6c885802009-02-28 21:56:50 +00004518 if (NewVD->isFileVarDecl())
4519 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004520 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00004521 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00004522 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004523 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00004524 else
4525 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004526 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004527 NewVD->setInvalidDecl();
4528 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004529 }
4530
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004531 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00004532 if (NewVD->isFileVarDecl())
4533 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4534 else
4535 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004536 NewVD->setInvalidDecl();
4537 return false;
Anders Carlsson6c885802009-02-28 21:56:50 +00004538 }
Mike Stump11289f42009-09-09 15:08:12 +00004539
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004540 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4541 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00004542 }
4543
John McCall1f82f242009-11-18 22:49:29 +00004544 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004545 // Since we did not find anything by this name and we're declaring
4546 // an extern "C" variable, look for a non-visible extern "C"
4547 // declaration with the same name.
4548 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00004549 = findLocallyScopedExternalDecl(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004550 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004551 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004552 }
4553
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004554 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004555 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4556 << T;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004557 NewVD->setInvalidDecl();
4558 return false;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004559 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004560
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004561 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004562 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004563 NewVD->setInvalidDecl();
4564 return false;
Mike Stumpe9efa802009-04-30 00:19:40 +00004565 }
Mike Stump11289f42009-09-09 15:08:12 +00004566
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004567 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004568 Diag(NewVD->getLocation(), diag::err_block_on_vm);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004569 NewVD->setInvalidDecl();
4570 return false;
Mike Stumpa7128632009-05-01 23:41:47 +00004571 }
4572
Richard Smith6331c402012-02-13 22:16:19 +00004573 if (NewVD->isConstexpr() && !T->isDependentType() &&
4574 RequireLiteralType(NewVD->getLocation(), T,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00004575 diag::err_constexpr_var_non_literal)) {
Richard Smith6331c402012-02-13 22:16:19 +00004576 NewVD->setInvalidDecl();
4577 return false;
4578 }
4579
John McCall1f82f242009-11-18 22:49:29 +00004580 if (!Previous.empty()) {
John McCall1f82f242009-11-18 22:49:29 +00004581 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004582 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004583 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004584 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004585}
4586
Douglas Gregor36d1b142009-10-06 17:59:45 +00004587/// \brief Data used with FindOverriddenMethod
4588struct FindOverriddenMethodData {
4589 Sema *S;
4590 CXXMethodDecl *Method;
4591};
4592
4593/// \brief Member lookup function that determines whether a given C++
4594/// method overrides a method in a base class, to be used with
4595/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004596static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004597 CXXBasePath &Path,
4598 void *UserData) {
4599 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004600
Douglas Gregor36d1b142009-10-06 17:59:45 +00004601 FindOverriddenMethodData *Data
4602 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004603
4604 DeclarationName Name = Data->Method->getDeclName();
4605
4606 // FIXME: Do we care about other names here too?
4607 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004608 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004609 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4610 CanQualType CT = Data->S->Context.getCanonicalType(T);
4611
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004612 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004613 }
4614
4615 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004616 Path.Decls.first != Path.Decls.second;
4617 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004618 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004619 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4620 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004621 return true;
4622 }
4623 }
4624
4625 return false;
4626}
4627
Douglas Gregor433e0532012-04-16 18:27:27 +00004628static bool hasDelayedExceptionSpec(CXXMethodDecl *Method) {
4629 const FunctionProtoType *Proto =Method->getType()->getAs<FunctionProtoType>();
4630 return Proto && Proto->getExceptionSpecType() == EST_Delayed;
4631}
4632
Sebastian Redld5b24532009-11-18 21:51:29 +00004633/// AddOverriddenMethods - See if a method overrides any in the base classes,
4634/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004635bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004636 // Look for virtual methods in base classes that this method might override.
4637 CXXBasePaths Paths;
4638 FindOverriddenMethodData Data;
4639 Data.Method = MD;
4640 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004641 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004642 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4643 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4644 E = Paths.found_decls_end(); I != E; ++I) {
4645 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00004646 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00004647 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Douglas Gregor433e0532012-04-16 18:27:27 +00004648 (hasDelayedExceptionSpec(MD) ||
4649 !CheckOverridingFunctionExceptionSpec(MD, OldMD)) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004650 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004651 AddedAny = true;
4652 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004653 }
4654 }
4655 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004656
4657 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004658}
4659
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004660namespace {
4661 // Struct for holding all of the extra arguments needed by
4662 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4663 struct ActOnFDArgs {
4664 Scope *S;
4665 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004666 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004667 bool AddToScope;
4668 };
4669}
4670
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004671namespace {
4672
4673// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004674// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004675class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4676 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004677 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
4678 CXXRecordDecl *Parent)
4679 : Context(Context), OriginalFD(TypoFD),
4680 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004681
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004682 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004683 if (candidate.getEditDistance() == 0)
4684 return false;
4685
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004686 llvm::SmallVector<unsigned, 1> MismatchedParams;
4687 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4688 CDeclEnd = candidate.end();
4689 CDecl != CDeclEnd; ++CDecl) {
4690 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4691
4692 if (FD && !FD->hasBody() &&
4693 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
4694 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4695 CXXRecordDecl *Parent = MD->getParent();
4696 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
4697 return true;
4698 } else if (!ExpectedParent) {
4699 return true;
4700 }
4701 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004702 }
4703
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004704 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004705 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004706
4707 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004708 ASTContext &Context;
4709 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004710 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004711};
4712
4713}
4714
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004715/// \brief Generate diagnostics for an invalid function redeclaration.
4716///
4717/// This routine handles generating the diagnostic messages for an invalid
4718/// function redeclaration, including finding possible similar declarations
4719/// or performing typo correction if there are no previous declarations with
4720/// the same name.
4721///
4722/// Returns a NamedDecl iff typo correction was performed and substituting in
4723/// the new declaration name does not cause new errors.
4724static NamedDecl* DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004725 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004726 ActOnFDArgs &ExtraArgs) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004727 NamedDecl *Result = NULL;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004728 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004729 DeclContext *NewDC = NewFD->getDeclContext();
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004730 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
John McCallf7cfb222010-10-13 05:45:15 +00004731 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004732 llvm::SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004733 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4734 TypoCorrection Correction;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004735 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004736 ExtraArgs.D.getDeclSpec().isFriendSpecified());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004737 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4738 : diag::err_member_def_does_not_match;
4739
4740 NewFD->setInvalidDecl();
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004741 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00004742 assert(!Prev.isAmbiguous() &&
4743 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00004744 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004745 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
4746 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004747 if (!Prev.empty()) {
4748 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4749 Func != FuncEnd; ++Func) {
4750 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004751 if (FD &&
4752 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004753 // Add 1 to the index so that 0 can mean the mismatch didn't
4754 // involve a parameter
4755 unsigned ParamNum =
4756 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4757 NearMatches.push_back(std::make_pair(FD, ParamNum));
4758 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004759 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004760 // If the qualified name lookup yielded nothing, try typo correction
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004761 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00004762 Prev.getLookupKind(), 0, 0,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004763 Validator, NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004764 // Trap errors.
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004765 Sema::SFINAETrap Trap(SemaRef);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004766
4767 // Set up everything for the call to ActOnFunctionDeclarator
4768 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4769 ExtraArgs.D.getIdentifierLoc());
4770 Previous.clear();
4771 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004772 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4773 CDeclEnd = Correction.end();
4774 CDecl != CDeclEnd; ++CDecl) {
4775 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00004776 if (FD && !FD->hasBody() &&
4777 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004778 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004779 }
4780 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004781 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004782 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4783 // pieces need to verify the typo-corrected C++ declaraction and hopefully
4784 // eliminate the need for the parameter pack ExtraArgs.
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004785 Result = SemaRef.ActOnFunctionDeclarator(
4786 ExtraArgs.S, ExtraArgs.D,
4787 Correction.getCorrectionDecl()->getDeclContext(),
4788 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4789 ExtraArgs.AddToScope);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004790 if (Trap.hasErrorOccurred()) {
4791 // Pretend the typo correction never occurred
4792 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4793 ExtraArgs.D.getIdentifierLoc());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004794 ExtraArgs.D.setRedeclaration(wasRedeclaration);
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004795 Previous.clear();
4796 Previous.setLookupName(Name);
4797 Result = NULL;
4798 } else {
4799 for (LookupResult::iterator Func = Previous.begin(),
4800 FuncEnd = Previous.end();
4801 Func != FuncEnd; ++Func) {
4802 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4803 NearMatches.push_back(std::make_pair(FD, 0));
4804 }
4805 }
4806 if (NearMatches.empty()) {
4807 // Ignore the correction if it didn't yield any close FunctionDecl matches
4808 Correction = TypoCorrection();
4809 } else {
Kaelyn Uhrain7fbe2f72011-09-14 19:37:32 +00004810 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4811 : diag::err_member_def_does_not_match_suggest;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004812 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004813 }
4814
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00004815 if (Correction) {
4816 SourceRange FixItLoc(NewFD->getLocation());
4817 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
4818 if (Correction.getCorrectionSpecifier() && SS.isValid())
4819 FixItLoc.setBegin(SS.getBeginLoc());
4820 SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004821 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004822 << FixItHint::CreateReplacement(
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00004823 FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
4824 } else {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004825 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4826 << Name << NewDC << NewFD->getLocation();
Kaelyn Uhrain1dac08d2012-06-07 23:57:12 +00004827 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004828
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004829 bool NewFDisConst = false;
4830 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4831 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4832
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004833 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4834 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4835 NearMatch != NearMatchEnd; ++NearMatch) {
4836 FunctionDecl *FD = NearMatch->first;
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004837 bool FDisConst = false;
4838 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4839 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004840
4841 if (unsigned Idx = NearMatch->second) {
4842 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00004843 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
4844 if (Loc.isInvalid()) Loc = FD->getLocation();
4845 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004846 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4847 } else if (Correction) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004848 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004849 << Correction.getQuoted(SemaRef.getLangOpts());
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004850 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004851 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00004852 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00004853 } else
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00004854 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00004855 }
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004856 return Result;
John McCallf7cfb222010-10-13 05:45:15 +00004857}
4858
David Blaikie30d15442011-10-19 22:56:21 +00004859static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
4860 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004861 switch (D.getDeclSpec().getStorageClassSpec()) {
4862 default: llvm_unreachable("Unknown storage class!");
4863 case DeclSpec::SCS_auto:
4864 case DeclSpec::SCS_register:
4865 case DeclSpec::SCS_mutable:
4866 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4867 diag::err_typecheck_sclass_func);
4868 D.setInvalidType();
4869 break;
4870 case DeclSpec::SCS_unspecified: break;
4871 case DeclSpec::SCS_extern: return SC_Extern;
4872 case DeclSpec::SCS_static: {
4873 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4874 // C99 6.7.1p5:
4875 // The declaration of an identifier for a function that has
4876 // block scope shall have no explicit storage-class specifier
4877 // other than extern
4878 // See also (C++ [dcl.stc]p4).
4879 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4880 diag::err_static_block_func);
4881 break;
4882 } else
4883 return SC_Static;
4884 }
4885 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4886 }
4887
4888 // No explicit storage class has already been returned
4889 return SC_None;
4890}
4891
4892static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4893 DeclContext *DC, QualType &R,
4894 TypeSourceInfo *TInfo,
4895 FunctionDecl::StorageClass SC,
4896 bool &IsVirtualOkay) {
4897 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4898 DeclarationName Name = NameInfo.getName();
4899
4900 FunctionDecl *NewFD = 0;
4901 bool isInline = D.getDeclSpec().isInlineSpecified();
4902 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4903 FunctionDecl::StorageClass SCAsWritten
4904 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4905
David Blaikiebbafb8a2012-03-11 07:00:24 +00004906 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004907 // Determine whether the function was written with a
4908 // prototype. This true when:
4909 // - there is a prototype in the declarator, or
4910 // - the type R of the function is some kind of typedef or other reference
4911 // to a type name (which eventually refers to a function type).
4912 bool HasPrototype =
4913 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4914 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4915
David Blaikie30d15442011-10-19 22:56:21 +00004916 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004917 D.getLocStart(), NameInfo, R,
David Blaikie30d15442011-10-19 22:56:21 +00004918 TInfo, SC, SCAsWritten, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004919 HasPrototype);
4920 if (D.isInvalidType())
4921 NewFD->setInvalidDecl();
4922
4923 // Set the lexical context.
4924 NewFD->setLexicalDeclContext(SemaRef.CurContext);
4925
4926 return NewFD;
4927 }
4928
4929 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4930 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4931
4932 // Check that the return type is not an abstract class type.
4933 // For record types, this is done by the AbstractClassUsageDiagnoser once
4934 // the class has been completely parsed.
4935 if (!DC->isRecord() &&
4936 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4937 R->getAs<FunctionType>()->getResultType(),
4938 diag::err_abstract_type_in_decl,
4939 SemaRef.AbstractReturnType))
4940 D.setInvalidType();
4941
4942 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4943 // This is a C++ constructor declaration.
4944 assert(DC->isRecord() &&
4945 "Constructors can only be declared in a member context");
4946
4947 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4948 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004949 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004950 R, TInfo, isExplicit, isInline,
4951 /*isImplicitlyDeclared=*/false,
4952 isConstexpr);
4953
4954 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4955 // This is a C++ destructor declaration.
4956 if (DC->isRecord()) {
4957 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4958 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4959 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4960 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004961 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004962 NameInfo, R, TInfo, isInline,
4963 /*isImplicitlyDeclared=*/false);
4964
4965 // If the class is complete, then we now create the implicit exception
4966 // specification. If the class is incomplete or dependent, we can't do
4967 // it yet.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004968 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004969 Record->getDefinition() && !Record->isBeingDefined() &&
4970 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4971 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4972 }
4973
4974 IsVirtualOkay = true;
4975 return NewDD;
4976
4977 } else {
4978 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4979 D.setInvalidType();
4980
4981 // Create a FunctionDecl to satisfy the function definition parsing
4982 // code path.
4983 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004984 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00004985 D.getIdentifierLoc(), Name, R, TInfo,
4986 SC, SCAsWritten, isInline,
4987 /*hasPrototype=*/true, isConstexpr);
4988 }
4989
4990 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4991 if (!DC->isRecord()) {
4992 SemaRef.Diag(D.getIdentifierLoc(),
4993 diag::err_conv_function_not_member);
4994 return 0;
4995 }
4996
4997 SemaRef.CheckConversionDeclarator(D, R, SC);
4998 IsVirtualOkay = true;
4999 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005000 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005001 R, TInfo, isInline, isExplicit,
5002 isConstexpr, SourceLocation());
5003
5004 } else if (DC->isRecord()) {
5005 // If the name of the function is the same as the name of the record,
5006 // then this must be an invalid constructor that has a return type.
5007 // (The parser checks for a return type and makes the declarator a
5008 // constructor if it has no return type).
5009 if (Name.getAsIdentifierInfo() &&
5010 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5011 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5012 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5013 << SourceRange(D.getIdentifierLoc());
5014 return 0;
5015 }
5016
5017 bool isStatic = SC == SC_Static;
5018
5019 // [class.free]p1:
5020 // Any allocation function for a class T is a static member
5021 // (even if not explicitly declared static).
5022 if (Name.getCXXOverloadedOperator() == OO_New ||
5023 Name.getCXXOverloadedOperator() == OO_Array_New)
5024 isStatic = true;
5025
5026 // [class.free]p6 Any deallocation function for a class X is a static member
5027 // (even if not explicitly declared static).
5028 if (Name.getCXXOverloadedOperator() == OO_Delete ||
5029 Name.getCXXOverloadedOperator() == OO_Array_Delete)
5030 isStatic = true;
5031
5032 IsVirtualOkay = !isStatic;
5033
5034 // This is a C++ method declaration.
5035 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005036 D.getLocStart(), NameInfo, R,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005037 TInfo, isStatic, SCAsWritten, isInline,
5038 isConstexpr, SourceLocation());
5039
5040 } else {
5041 // Determine whether the function was written with a
5042 // prototype. This true when:
5043 // - we're in C++ (where every function has a prototype),
5044 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005045 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005046 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5047 true/*HasPrototype*/, isConstexpr);
5048 }
5049}
5050
Mike Stump11289f42009-09-09 15:08:12 +00005051NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00005052Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005053 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00005054 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005055 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005056 QualType R = TInfo->getType();
5057
Zhongxing Xubece5d62009-01-16 01:13:29 +00005058 assert(R.getTypePtr()->isFunctionType());
5059
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005060 // TODO: consider using NameInfo for diagnostic.
5061 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5062 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005063 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005064
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005065 if (D.getDeclSpec().isThreadSpecified())
5066 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5067
Chris Lattner347eec92009-04-11 19:17:25 +00005068 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00005069 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00005070 Diag(D.getIdentifierLoc(),
5071 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005072 << R->getAs<FunctionType>()->getResultType()
5073 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005074
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005075 QualType T = R->getAs<FunctionType>()->getResultType();
5076 T = Context.getObjCObjectPointerType(T);
5077 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5078 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5079 R = Context.getFunctionType(T, FPT->arg_type_begin(),
5080 FPT->getNumArgs(), EPI);
5081 }
5082 else if (isa<FunctionNoProtoType>(R))
5083 R = Context.getFunctionNoProtoType(T);
Chris Lattner347eec92009-04-11 19:17:25 +00005084 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005085
Douglas Gregor513e63c2010-12-10 19:28:19 +00005086 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00005087 FunctionTemplateDecl *FunctionTemplate = 0;
5088 bool isExplicitSpecialization = false;
5089 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00005090
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005091 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00005092 bool HasExplicitTemplateArgs = false;
5093 TemplateArgumentListInfo TemplateArgs;
5094
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005095 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00005096
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005097 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5098 isVirtualOkay);
5099 if (!NewFD) return 0;
5100
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00005101 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5102 NewFD->setTopLevelDeclInObjCContainer();
5103
David Blaikiebbafb8a2012-03-11 07:00:24 +00005104 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005105 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00005106 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5107 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00005108 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005109 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005110 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00005111 // C++ [class.friend]p5
5112 // A function can be defined in a friend declaration of a
5113 // class . . . . Such a function is implicitly inline.
5114 NewFD->setImplicitlyInline();
5115 }
5116
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005117 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005118 isExplicitSpecialization = false;
5119 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005120 if (D.isInvalidType())
5121 NewFD->setInvalidDecl();
5122
5123 // Set the lexical context. If the declarator has a C++
5124 // scope specifier, or is the object of a friend declaration, the
5125 // lexical context will be different from the semantic context.
5126 NewFD->setLexicalDeclContext(CurContext);
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005127
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005128 // Match up the template parameter lists with the scope specifier, then
5129 // determine whether we have a template or a template specialization.
5130 bool Invalid = false;
5131 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00005132 = MatchTemplateParametersToScopeSpecifier(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005133 D.getDeclSpec().getLocStart(),
Douglas Gregor972fe532011-05-10 18:27:06 +00005134 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00005135 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00005136 TemplateParamLists.get(),
5137 TemplateParamLists.size(),
5138 isFriend,
5139 isExplicitSpecialization,
5140 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00005141 if (TemplateParams->size() > 0) {
5142 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005143
Abramo Bagnara60804e12011-03-18 15:16:37 +00005144 // Check that we can declare a template here.
5145 if (CheckTemplateDeclScope(S, TemplateParams))
5146 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005147
Abramo Bagnara60804e12011-03-18 15:16:37 +00005148 // A destructor cannot be a template.
5149 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5150 Diag(NewFD->getLocation(), diag::err_destructor_template);
5151 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00005152 }
Douglas Gregor041b0842011-10-14 15:31:12 +00005153
5154 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00005155 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00005156 // now that we know what the current instantiation is.
5157 if (DC->isDependentContext()) {
5158 ContextRAII SavedContext(*this, DC);
5159 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5160 Invalid = true;
5161 }
5162
John McCall1f0479e2010-03-24 08:27:58 +00005163
Abramo Bagnara60804e12011-03-18 15:16:37 +00005164 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5165 NewFD->getLocation(),
5166 Name, TemplateParams,
5167 NewFD);
5168 FunctionTemplate->setLexicalDeclContext(CurContext);
5169 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5170
5171 // For source fidelity, store the other template param lists.
5172 if (TemplateParamLists.size() > 1) {
5173 NewFD->setTemplateParameterListsInfo(Context,
5174 TemplateParamLists.size() - 1,
5175 TemplateParamLists.release());
5176 }
5177 } else {
5178 // This is a function template specialization.
5179 isFunctionTemplateSpecialization = true;
5180 // For source fidelity, store all the template param lists.
5181 NewFD->setTemplateParameterListsInfo(Context,
5182 TemplateParamLists.size(),
5183 TemplateParamLists.release());
5184
5185 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5186 if (isFriend) {
5187 // We want to remove the "template<>", found here.
5188 SourceRange RemoveRange = TemplateParams->getSourceRange();
5189
5190 // If we remove the template<> and the name is not a
5191 // template-id, we're actually silently creating a problem:
5192 // the friend declaration will refer to an untemplated decl,
5193 // and clearly the user wants a template specialization. So
5194 // we need to insert '<>' after the name.
5195 SourceLocation InsertLoc;
5196 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5197 InsertLoc = D.getName().getSourceRange().getEnd();
5198 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5199 }
5200
5201 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5202 << Name << RemoveRange
5203 << FixItHint::CreateRemoval(RemoveRange)
5204 << FixItHint::CreateInsertion(InsertLoc, "<>");
5205 }
5206 }
5207 }
5208 else {
5209 // All template param lists were matched against the scope specifier:
5210 // this is NOT (an explicit specialization of) a template.
5211 if (TemplateParamLists.size() > 0)
5212 // For source fidelity, store all the template param lists.
5213 NewFD->setTemplateParameterListsInfo(Context,
5214 TemplateParamLists.size(),
5215 TemplateParamLists.release());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005216 }
5217
5218 if (Invalid) {
5219 NewFD->setInvalidDecl();
5220 if (FunctionTemplate)
5221 FunctionTemplate->setInvalidDecl();
5222 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005223
Richard Smithd069d2f2012-01-06 01:31:20 +00005224 // If we see "T var();" at block scope, where T is a class type, it is
5225 // probably an attempt to initialize a variable, not a function declaration.
5226 // We don't catch this case earlier, since there is no ambiguity here.
5227 if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
5228 CurContext->isFunctionOrMethod() &&
5229 D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
5230 D.getDeclSpec().getStorageClassSpecAsWritten()
5231 == DeclSpec::SCS_unspecified) {
5232 QualType T = R->getAs<FunctionType>()->getResultType();
5233 DeclaratorChunk &C = D.getTypeObject(0);
Richard Smithb3851f52012-01-06 02:30:50 +00005234 if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
Richard Smith700537c2012-06-12 01:51:59 +00005235 !C.Fun.hasTrailingReturnType() &&
Richard Smithd069d2f2012-01-06 01:31:20 +00005236 C.Fun.getExceptionSpecType() == EST_None) {
Richard Smith8d06f422012-01-12 23:53:29 +00005237 SourceRange ParenRange(C.Loc, C.EndLoc);
5238 Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5239
5240 // If the declaration looks like:
5241 // T var1,
5242 // f();
5243 // and name lookup finds a function named 'f', then the ',' was
5244 // probably intended to be a ';'.
5245 if (!D.isFirstDeclarator() && D.getIdentifier()) {
5246 FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5247 FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5248 if (Comma.getFileID() != Name.getFileID() ||
5249 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5250 LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5251 LookupOrdinaryName);
5252 if (LookupName(Result, S))
5253 Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5254 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5255 }
5256 }
5257 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5258 // Empty parens mean value-initialization, and no parens mean default
5259 // initialization. These are equivalent if the default constructor is
5260 // user-provided, or if zero-initialization is a no-op.
Richard Smith90b748e2012-01-13 02:14:39 +00005261 if (RD && RD->hasDefinition() &&
5262 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
Richard Smith8d06f422012-01-12 23:53:29 +00005263 Diag(C.Loc, diag::note_empty_parens_default_ctor)
5264 << FixItHint::CreateRemoval(ParenRange);
David Blaikie7665a622012-04-30 18:27:22 +00005265 else {
5266 std::string Init = getFixItZeroInitializerForType(T);
5267 if (Init.empty() && LangOpts.CPlusPlus0x)
5268 Init = "{}";
5269 if (!Init.empty())
5270 Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5271 << FixItHint::CreateReplacement(ParenRange, Init);
5272 }
Richard Smithd069d2f2012-01-06 01:31:20 +00005273 }
5274 }
5275
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005276 // C++ [dcl.fct.spec]p5:
5277 // The virtual specifier shall only be used in declarations of
5278 // nonstatic class member functions that appear within a
5279 // member-specification of a class declaration; see 10.3.
5280 //
5281 if (isVirtual && !NewFD->isInvalidDecl()) {
5282 if (!isVirtualOkay) {
5283 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5284 diag::err_virtual_non_function);
5285 } else if (!CurContext->isRecord()) {
5286 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00005287 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5288 diag::err_virtual_out_of_class)
5289 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5290 } else if (NewFD->getDescribedFunctionTemplate()) {
5291 // C++ [temp.mem]p3:
5292 // A member function template shall not be virtual.
5293 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5294 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005295 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5296 } else {
5297 // Okay: Add virtual to the method.
5298 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00005299 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00005300 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005301
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005302 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00005303 // The inline specifier shall not appear on a block scope function
5304 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005305 if (isInline && !NewFD->isInvalidDecl()) {
5306 if (CurContext->isFunctionOrMethod()) {
5307 // 'inline' is not allowed on block scope function declaration.
5308 Diag(D.getDeclSpec().getInlineSpecLoc(),
5309 diag::err_inline_declaration_block_scope) << Name
5310 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5311 }
5312 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005313
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005314 // C++ [dcl.fct.spec]p6:
5315 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00005316 // constructor or conversion function within its class definition;
5317 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005318 if (isExplicit && !NewFD->isInvalidDecl()) {
5319 if (!CurContext->isRecord()) {
5320 // 'explicit' was specified outside of the class.
5321 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5322 diag::err_explicit_out_of_class)
5323 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5324 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5325 !isa<CXXConversionDecl>(NewFD)) {
5326 // 'explicit' was specified on a function that wasn't a constructor
5327 // or conversion function.
5328 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5329 diag::err_explicit_non_ctor_or_conv_function)
5330 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5331 }
5332 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005333
Richard Smitha77a0a62011-08-15 21:04:07 +00005334 if (isConstexpr) {
5335 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5336 // are implicitly inline.
5337 NewFD->setImplicitlyInline();
5338
Richard Smitha77a0a62011-08-15 21:04:07 +00005339 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5340 // be either constructors or to return a literal type. Therefore,
5341 // destructors cannot be declared constexpr.
5342 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00005343 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00005344 }
5345
Douglas Gregor26701a42011-09-09 02:06:17 +00005346 // If __module_private__ was specified, mark the function accordingly.
5347 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005348 if (isFunctionTemplateSpecialization) {
5349 SourceLocation ModulePrivateLoc
5350 = D.getDeclSpec().getModulePrivateSpecLoc();
5351 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5352 << 0
5353 << FixItHint::CreateRemoval(ModulePrivateLoc);
5354 } else {
5355 NewFD->setModulePrivate();
5356 if (FunctionTemplate)
5357 FunctionTemplate->setModulePrivate();
5358 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005359 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005360
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005361 if (isFriend) {
5362 // For now, claim that the objects have no previous declaration.
5363 if (FunctionTemplate) {
5364 FunctionTemplate->setObjectOfFriendDecl(false);
5365 FunctionTemplate->setAccess(AS_public);
5366 }
5367 NewFD->setObjectOfFriendDecl(false);
5368 NewFD->setAccess(AS_public);
5369 }
5370
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005371 // If a function is defined as defaulted or deleted, mark it as such now.
5372 switch (D.getFunctionDefinitionKind()) {
5373 case FDK_Declaration:
5374 case FDK_Definition:
5375 break;
5376
5377 case FDK_Defaulted:
5378 NewFD->setDefaulted();
5379 break;
5380
5381 case FDK_Deleted:
5382 NewFD->setDeletedAsWritten();
5383 break;
5384 }
5385
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005386 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5387 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00005388 // C++ [class.mfct]p2:
5389 // A member function may be defined (8.4) in its class definition, in
5390 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00005391 NewFD->setImplicitlyInline();
5392 }
5393
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005394 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5395 !CurContext->isRecord()) {
5396 // C++ [class.static]p1:
5397 // A data or function member of a class may be declared static
5398 // in a class definition, in which case it is a static member of
5399 // the class.
5400
5401 // Complain about the 'static' specifier if it's on an out-of-line
5402 // member function definition.
5403 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5404 diag::err_static_out_of_line)
5405 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5406 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005407 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00005408
5409 // Filter out previous declarations that don't match the scope.
5410 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5411 isExplicitSpecialization ||
5412 isFunctionTemplateSpecialization);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005413
Zhongxing Xubece5d62009-01-16 01:13:29 +00005414 // Handle GNU asm-label extension (encoded as an attribute).
5415 if (Expr *E = (Expr*) D.getAsmLabel()) {
5416 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005417 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005418 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5419 SE->getString()));
David Chisnall0867d9c2012-02-18 16:12:34 +00005420 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5421 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5422 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5423 if (I != ExtnameUndeclaredIdentifiers.end()) {
5424 NewFD->addAttr(I->second);
5425 ExtnameUndeclaredIdentifiers.erase(I);
5426 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005427 }
5428
Chris Lattner9af40c12009-04-25 06:12:16 +00005429 // Copy the parameter declarations from the declarator D to the function
5430 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005431 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00005432 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005433 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00005434
Zhongxing Xubece5d62009-01-16 01:13:29 +00005435 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5436 // function that takes no arguments, not a function that takes a
5437 // single void argument.
5438 // We let through "const void" here because Sema::GetTypeForDeclarator
5439 // already checks for that case.
5440 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5441 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005442 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00005443 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00005444 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005445
5446 // In C++, the empty parameter-type-list must be spelled "void"; a
5447 // typedef of void is not permitted.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005448 if (getLangOpts().CPlusPlus &&
Richard Smithdda56e42011-04-15 14:24:37 +00005449 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5450 bool IsTypeAlias = false;
5451 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5452 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005453 else if (const TemplateSpecializationType *TST =
5454 Param->getType()->getAs<TemplateSpecializationType>())
5455 IsTypeAlias = TST->isTypeAlias();
Richard Smithdda56e42011-04-15 14:24:37 +00005456 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5457 << IsTypeAlias;
5458 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005459 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005460 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00005461 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005462 assert(Param->getDeclContext() != NewFD && "Was set before ?");
5463 Param->setDeclContext(NewFD);
5464 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00005465
5466 if (Param->isInvalidDecl())
5467 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005468 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005469 }
Mike Stump11289f42009-09-09 15:08:12 +00005470
John McCall9dd450b2009-09-21 23:43:11 +00005471 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00005472 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00005473 // following example, we'll need to synthesize (unnamed)
5474 // parameters for use in the declaration.
5475 //
5476 // @code
5477 // typedef void fn(int);
5478 // fn f;
5479 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005480
Chris Lattner47c0d002009-04-25 06:03:53 +00005481 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00005482 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5483 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00005484 ParmVarDecl *Param =
5485 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00005486 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00005487 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00005488 }
Chris Lattner49303b22009-04-25 18:38:18 +00005489 } else {
5490 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5491 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00005492 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005493
Chris Lattner9af40c12009-04-25 06:12:16 +00005494 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00005495 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00005496
James Molloy6f8780b2012-02-29 10:24:19 +00005497 // Find all anonymous symbols defined during the declaration of this function
5498 // and add to NewFD. This lets us track decls such 'enum Y' in:
5499 //
5500 // void f(enum Y {AA} x) {}
5501 //
5502 // which would otherwise incorrectly end up in the translation unit scope.
5503 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5504 DeclsInPrototypeScope.clear();
5505
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005506 // Process the non-inheritable attributes on this declaration.
5507 ProcessDeclAttributes(S, NewFD, D,
5508 /*NonInheritable=*/true, /*Inheritable=*/false);
5509
Richard Smith84208dc2012-03-13 05:56:40 +00005510 // Functions returning a variably modified type violate C99 6.7.5.2p2
5511 // because all functions have linkage.
5512 if (!NewFD->isInvalidDecl() &&
5513 NewFD->getResultType()->isVariablyModifiedType()) {
5514 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5515 NewFD->setInvalidDecl();
5516 }
5517
Rafael Espindolac67f2232012-05-10 02:50:16 +00005518 // Handle attributes.
5519 ProcessDeclAttributes(S, NewFD, D,
5520 /*NonInheritable=*/false, /*Inheritable=*/true);
5521
David Blaikiebbafb8a2012-03-11 07:00:24 +00005522 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005523 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00005524 bool isExplicitSpecialization=false;
David Blaikied937bf12011-09-08 06:33:04 +00005525 if (!NewFD->isInvalidDecl()) {
Richard Smith84208dc2012-03-13 05:56:40 +00005526 if (NewFD->isMain())
5527 CheckMain(NewFD, D.getDeclSpec());
5528 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5529 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00005530 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005531 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005532 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5533 "previous declaration set still overloaded");
5534 } else {
5535 // If the declarator is a template-id, translate the parser's template
5536 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005537 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5538 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5539 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5540 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5541 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5542 TemplateId->getTemplateArgs(),
5543 TemplateId->NumArgs);
5544 translateTemplateArguments(TemplateArgsPtr,
5545 TemplateArgs);
5546 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00005547
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005548 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00005549
Douglas Gregor522d5eb2011-06-06 15:22:55 +00005550 if (NewFD->isInvalidDecl()) {
5551 HasExplicitTemplateArgs = false;
5552 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00005553 // Function template with explicit template arguments.
5554 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5555 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5556
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005557 HasExplicitTemplateArgs = false;
5558 } else if (!isFunctionTemplateSpecialization &&
5559 !D.getDeclSpec().isFriendSpecified()) {
5560 // We have encountered something that the user meant to be a
5561 // specialization (because it has explicitly-specified template
5562 // arguments) but that was not introduced with a "template<>" (or had
5563 // too few of them).
5564 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5565 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5566 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005567 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00005568 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005569 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00005570 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005571 // "friend void foo<>(int);" is an implicit specialization decl.
5572 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00005573 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005574 } else if (isFriend && isFunctionTemplateSpecialization) {
5575 // This combination is only possible in a recovery case; the user
5576 // wrote something like:
5577 // template <> friend void foo(int);
5578 // which we're recovering from as if the user had written:
5579 // friend void foo<>(int);
5580 // Go ahead and fake up a template id.
5581 HasExplicitTemplateArgs = true;
5582 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5583 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005584 }
John McCallf7cfb222010-10-13 05:45:15 +00005585
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005586 // If it's a friend (and only if it's a friend), it's possible
5587 // that either the specialized function type or the specialized
5588 // template is dependent, and therefore matching will fail. In
5589 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00005590 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005591 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00005592 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5593 TemplateSpecializationType::anyDependentTemplateArguments(
5594 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5595 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005596 assert(HasExplicitTemplateArgs &&
5597 "friend function specialization without template args");
5598 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5599 Previous))
5600 NewFD->setInvalidDecl();
5601 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00005602 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00005603 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005604 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005605 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005606 diag::ext_function_specialization_in_class :
5607 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00005608 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00005609 } else if (CheckFunctionTemplateSpecialization(NewFD,
5610 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5611 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005612 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00005613
5614 // C++ [dcl.stc]p1:
5615 // A storage-class-specifier shall not be specified in an explicit
5616 // specialization (14.7.3)
5617 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00005618 if (SC != NewFD->getStorageClass())
5619 Diag(NewFD->getLocation(),
5620 diag::err_explicit_specialization_inconsistent_storage_class)
5621 << SC
5622 << FixItHint::CreateRemoval(
5623 D.getDeclSpec().getStorageClassSpecLoc());
5624
5625 else
5626 Diag(NewFD->getLocation(),
5627 diag::ext_explicit_specialization_storage_class)
5628 << FixItHint::CreateRemoval(
5629 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00005630 }
5631
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005632 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5633 if (CheckMemberSpecialization(NewFD, Previous))
5634 NewFD->setInvalidDecl();
5635 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005636
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005637 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00005638 if (!isDependentClassScopeExplicitSpecialization) {
5639 if (NewFD->isInvalidDecl()) {
5640 // If this is a class member, mark the class invalid immediately.
5641 // This avoids some consistency errors later.
5642 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5643 methodDecl->getParent()->setInvalidDecl();
5644 } else {
5645 if (NewFD->isMain())
5646 CheckMain(NewFD, D.getDeclSpec());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005647 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5648 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00005649 }
5650 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005651
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005652 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005653 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5654 "previous declaration set still overloaded");
5655
5656 NamedDecl *PrincipalDecl = (FunctionTemplate
5657 ? cast<NamedDecl>(FunctionTemplate)
5658 : NewFD);
5659
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005660 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005661 AccessSpecifier Access = AS_public;
5662 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00005663 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005664
5665 NewFD->setAccess(Access);
5666 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5667
5668 PrincipalDecl->setObjectOfFriendDecl(true);
5669 }
5670
5671 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5672 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5673 PrincipalDecl->setNonMemberOperator();
5674
5675 // If we have a function template, check the template parameter
5676 // list. This will check and merge default template arguments.
5677 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00005678 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00005679 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005680 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00005681 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005682 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005683 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005684 ? TPC_FriendFunctionTemplateDefinition
5685 : TPC_FriendFunctionTemplate)
5686 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00005687 DC && DC->isRecord() &&
5688 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00005689 ? TPC_ClassTemplateMember
5690 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005691 }
5692
5693 if (NewFD->isInvalidDecl()) {
5694 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005695 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005696 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005697 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005698 // Fake up an access specifier if it's supposed to be a class member.
5699 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5700 NewFD->setAccess(AS_public);
5701
5702 // Qualified decls generally require a previous declaration.
5703 if (D.getCXXScopeSpec().isSet()) {
5704 // ...with the major exception of templated-scope or
5705 // dependent-scope friend declarations.
5706
5707 // TODO: we currently also suppress this check in dependent
5708 // contexts because (1) the parameter depth will be off when
5709 // matching friend templates and (2) we might actually be
5710 // selecting a friend based on a dependent factor. But there
5711 // are situations where these conditions don't apply and we
5712 // can actually do this check immediately.
5713 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00005714 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005715 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5716 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005717 // ignore these
5718 } else {
5719 // The user tried to provide an out-of-line definition for a
5720 // function that is a member of a class or namespace, but there
5721 // was no such member function declared (C++ [class.mfct]p2,
5722 // C++ [namespace.memdef]p2). For example:
5723 //
5724 // class X {
5725 // void f() const;
5726 // };
5727 //
5728 // void X::f() { } // ill-formed
5729 //
5730 // Complain about this problem, and attempt to suggest close
5731 // matches (e.g., those that differ only in cv-qualifiers and
5732 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005733
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005734 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005735 NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005736 ExtraArgs)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005737 AddToScope = ExtraArgs.AddToScope;
5738 return Result;
5739 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00005740 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005741
5742 // Unqualified local friend declarations are required to resolve
5743 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005744 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005745 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00005746 NewFD,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005747 ExtraArgs)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005748 AddToScope = ExtraArgs.AddToScope;
5749 return Result;
5750 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00005751 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005752
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005753 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005754 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00005755 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005756 // An out-of-line member function declaration must also be a
5757 // definition (C++ [dcl.meaning]p1).
5758 // Note that this is not the case for explicit specializations of
5759 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00005760 // C++ [temp.expl.spec]p2. We also allow these declarations as an
5761 // extension for compatibility with old SWIG code which likes to
5762 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005763 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5764 << D.getCXXScopeSpec().getRange();
5765 }
5766 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005767
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005768 AddKnownFunctionAttributes(NewFD);
5769
Douglas Gregor72609052010-08-06 13:50:58 +00005770 if (NewFD->hasAttr<OverloadableAttr>() &&
5771 !NewFD->getType()->getAs<FunctionProtoType>()) {
5772 Diag(NewFD->getLocation(),
5773 diag::err_attribute_overloadable_no_prototype)
5774 << NewFD;
5775
5776 // Turn this into a variadic function with no parameters.
5777 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005778 FunctionProtoType::ExtProtoInfo EPI;
5779 EPI.Variadic = true;
5780 EPI.ExtInfo = FT->getExtInfo();
5781
5782 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00005783 NewFD->setType(R);
5784 }
5785
Eli Friedman570024a2010-08-05 06:57:20 +00005786 // If there's a #pragma GCC visibility in scope, and this isn't a class
5787 // member, set the visibility of this function.
5788 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5789 AddPushedVisibilityAttribute(NewFD);
5790
John McCall32f5fe12011-09-30 05:12:12 +00005791 // If there's a #pragma clang arc_cf_code_audited in scope, consider
5792 // marking the function.
5793 AddCFAuditedAttribute(NewFD);
5794
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005795 // If this is a locally-scoped extern C function, update the
5796 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00005797 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005798 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00005799 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005800
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00005801 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00005802 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00005803
David Blaikiebbafb8a2012-03-11 07:00:24 +00005804 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005805 if (FunctionTemplate) {
5806 if (NewFD->isInvalidDecl())
5807 FunctionTemplate->setInvalidDecl();
5808 return FunctionTemplate;
5809 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005810 }
Mike Stump11289f42009-09-09 15:08:12 +00005811
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005812 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
5813 if ((getLangOpts().OpenCLVersion >= 120)
5814 && NewFD->hasAttr<OpenCLKernelAttr>()
5815 && (SC == SC_Static)) {
5816 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
5817 D.setInvalidType();
5818 }
5819
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005820 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005821
David Blaikiebbafb8a2012-03-11 07:00:24 +00005822 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005823 if (IdentifierInfo *II = NewFD->getIdentifier())
5824 if (!NewFD->isInvalidDecl() &&
5825 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5826 if (II->isStr("cudaConfigureCall")) {
5827 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5828 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5829
5830 Context.setcudaConfigureCallDecl(NewFD);
5831 }
5832 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005833
5834 // Here we have an function template explicit specialization at class scope.
5835 // The actually specialization will be postponed to template instatiation
5836 // time via the ClassScopeFunctionSpecializationDecl node.
5837 if (isDependentClassScopeExplicitSpecialization) {
5838 ClassScopeFunctionSpecializationDecl *NewSpec =
5839 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00005840 Context, CurContext, SourceLocation(),
5841 cast<CXXMethodDecl>(NewFD),
5842 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005843 CurContext->addDecl(NewSpec);
5844 AddToScope = false;
5845 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005846
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005847 return NewFD;
5848}
5849
5850/// \brief Perform semantic checking of a new function declaration.
5851///
5852/// Performs semantic analysis of the new function declaration
5853/// NewFD. This routine performs all semantic checking that does not
5854/// require the actual declarator involved in the declaration, and is
5855/// used both for the declaration of functions as they are parsed
5856/// (called via ActOnDeclarator) and for the declaration of functions
5857/// that have been instantiated via C++ template instantiation (called
5858/// via InstantiateDecl).
5859///
James Dennettffad8b72012-06-22 08:10:18 +00005860/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00005861/// an explicit specialization of the previous declaration.
5862///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005863/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005864///
James Dennettffad8b72012-06-22 08:10:18 +00005865/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005866bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00005867 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005868 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00005869 assert(!NewFD->getResultType()->isVariablyModifiedType()
5870 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00005871
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005872 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00005873 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005874 // Since we did not find anything by this name and we're declaring
5875 // an extern "C" function, look for a non-visible extern "C"
5876 // declaration with the same name.
5877 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00005878 = findLocallyScopedExternalDecl(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005879 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00005880 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005881 }
5882
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005883 bool Redeclaration = false;
5884
Douglas Gregore62c0a42009-02-24 01:23:02 +00005885 // Merge or overload the declaration with an existing declaration of
5886 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00005887 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00005888 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00005889 // a declaration that requires merging. If it's an overload,
5890 // there's no more work to do here; we'll just add the new
5891 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00005892
John McCall1f82f242009-11-18 22:49:29 +00005893 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00005894 if (!AllowOverloadingOfFunction(Previous, Context)) {
5895 Redeclaration = true;
5896 OldDecl = Previous.getFoundDecl();
5897 } else {
John McCalle9cccd82010-06-16 08:42:20 +00005898 switch (CheckOverload(S, NewFD, Previous, OldDecl,
5899 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00005900 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005901 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00005902 break;
5903
5904 case Ovl_NonFunction:
5905 Redeclaration = true;
5906 break;
5907
5908 case Ovl_Overload:
5909 Redeclaration = false;
5910 break;
John McCall1f82f242009-11-18 22:49:29 +00005911 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005912
David Blaikiebbafb8a2012-03-11 07:00:24 +00005913 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00005914 // If a function name is overloadable in C, then every function
5915 // with that name must be marked "overloadable".
5916 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5917 << Redeclaration << NewFD;
5918 NamedDecl *OverloadedDecl = 0;
5919 if (Redeclaration)
5920 OverloadedDecl = OldDecl;
5921 else if (!Previous.empty())
5922 OverloadedDecl = Previous.getRepresentativeDecl();
5923 if (OverloadedDecl)
5924 Diag(OverloadedDecl->getLocation(),
5925 diag::note_attribute_overloadable_prev_overload);
5926 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5927 Context));
5928 }
John McCall1f82f242009-11-18 22:49:29 +00005929 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005930
John McCall1f82f242009-11-18 22:49:29 +00005931 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005932 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00005933 // merged.
James Molloye9430032012-03-13 08:55:35 +00005934 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005935 NewFD->setInvalidDecl();
5936 return Redeclaration;
5937 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005938
John McCall1f82f242009-11-18 22:49:29 +00005939 Previous.clear();
5940 Previous.addDecl(OldDecl);
5941
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005942 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00005943 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
David Blaikie30d15442011-10-19 22:56:21 +00005944 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00005945 FunctionTemplateDecl *NewTemplateDecl
5946 = NewFD->getDescribedFunctionTemplate();
5947 assert(NewTemplateDecl && "Template/non-template mismatch");
5948 if (CXXMethodDecl *Method
5949 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5950 Method->setAccess(OldTemplateDecl->getAccess());
5951 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5952 }
Douglas Gregorcf915552009-10-13 16:30:37 +00005953
5954 // If this is an explicit specialization of a member that is a function
5955 // template, mark it as a member specialization.
5956 if (IsExplicitSpecialization &&
5957 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5958 NewTemplateDecl->setMemberSpecialization();
5959 assert(OldTemplateDecl->isMemberSpecialization());
5960 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00005961
Douglas Gregorca027af2009-10-12 22:27:17 +00005962 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005963 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5964 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005965 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005966 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005967 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00005968 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005969
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005970 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00005971 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005972 // C++-specific checks.
5973 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5974 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005975 } else if (CXXDestructorDecl *Destructor =
5976 dyn_cast<CXXDestructorDecl>(NewFD)) {
5977 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005978 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005979
Douglas Gregor7454c562010-07-02 20:37:36 +00005980 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00005981 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005982 if (!ClassType->isDependentType()) {
5983 DeclarationName Name
5984 = Context.DeclarationNames.getCXXDestructorName(
5985 Context.getCanonicalType(ClassType));
5986 if (NewFD->getDeclName() != Name) {
5987 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005988 NewFD->setInvalidDecl();
5989 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005990 }
5991 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005992 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00005993 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005994 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00005995 }
5996
5997 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00005998 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5999 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006000 !Method->getDescribedFunctionTemplate()) {
6001 if (AddOverriddenMethods(Method->getParent(), Method)) {
6002 // If the function was marked as "static", we have a problem.
6003 if (NewFD->getStorageClass() == SC_Static) {
6004 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
6005 << NewFD->getDeclName();
6006 for (CXXMethodDecl::method_iterator
6007 Overridden = Method->begin_overridden_methods(),
6008 OverriddenEnd = Method->end_overridden_methods();
6009 Overridden != OverriddenEnd;
6010 ++Overridden) {
6011 Diag((*Overridden)->getLocation(),
6012 diag::note_overridden_virtual_function);
6013 }
6014 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006015 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006016 }
Douglas Gregor3024f072012-04-16 07:05:22 +00006017
6018 if (Method->isStatic())
6019 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00006020 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006021
6022 // Extra checking for C++ overloaded operators (C++ [over.oper]).
6023 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006024 CheckOverloadedOperatorDeclaration(NewFD)) {
6025 NewFD->setInvalidDecl();
6026 return Redeclaration;
6027 }
Alexis Huntc88db062010-01-13 09:01:02 +00006028
6029 // Extra checking for C++0x literal operators (C++0x [over.literal]).
6030 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006031 CheckLiteralOperatorDeclaration(NewFD)) {
6032 NewFD->setInvalidDecl();
6033 return Redeclaration;
6034 }
Alexis Huntc88db062010-01-13 09:01:02 +00006035
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006036 // In C++, check default arguments now that we have merged decls. Unless
6037 // the lexical context is the class, because in this case this is done
6038 // during delayed parsing anyway.
6039 if (!CurContext->isRecord())
6040 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00006041
6042 // If this function declares a builtin function, check the type of this
6043 // declaration against the expected type for the builtin.
6044 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6045 ASTContext::GetBuiltinTypeError Error;
6046 QualType T = Context.GetBuiltinType(BuiltinID, Error);
6047 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6048 // The type of this function differs from the type of the builtin,
6049 // so forget about the builtin entirely.
6050 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6051 }
6052 }
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00006053
6054 // If this function is declared as being extern "C", then check to see if
6055 // the function returns a UDT (class, struct, or union type) that is not C
6056 // compatible, and if it does, warn the user.
6057 if (NewFD->isExternC()) {
6058 QualType R = NewFD->getResultType();
6059 if (!R.isPODType(Context) &&
6060 !R->isVoidType())
6061 Diag( NewFD->getLocation(), diag::warn_return_value_udt )
6062 << NewFD << R;
6063 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00006064 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006065 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00006066}
6067
David Blaikied937bf12011-09-08 06:33:04 +00006068void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00006069 // C++11 [basic.start.main]p3: A program that declares main to be inline,
6070 // static or constexpr is ill-formed.
John McCall02dee0a2009-07-25 04:36:53 +00006071 // C99 6.7.4p4: In a hosted environment, the inline function specifier
6072 // shall not appear in a declaration of main.
6073 // static main is not an error under C99, but we should warn about it.
David Blaikied937bf12011-09-08 06:33:04 +00006074 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00006075 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00006076 ? diag::err_static_main : diag::warn_static_main)
6077 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6078 if (FD->isInlineSpecified())
6079 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6080 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Richard Smith3f333f22012-02-04 06:10:17 +00006081 if (FD->isConstexpr()) {
6082 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6083 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6084 FD->setConstexpr(false);
6085 }
John McCall02dee0a2009-07-25 04:36:53 +00006086
6087 QualType T = FD->getType();
6088 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00006089 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00006090
John McCall5ed3caf2012-02-14 19:50:52 +00006091 // All the standards say that main() should should return 'int'.
6092 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6093 // In C and C++, main magically returns 0 if you fall off the end;
6094 // set the flag which tells us that.
6095 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6096 FD->setHasImplicitReturnZero(true);
6097
6098 // In C with GNU extensions we allow main() to have non-integer return
6099 // type, but we should warn about the extension, and we disable the
6100 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006101 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00006102 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6103
6104 // Otherwise, this is just a flat-out error.
6105 } else {
Douglas Gregorf05c0952011-02-19 19:04:23 +00006106 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00006107 FD->setInvalidDecl(true);
6108 }
6109
6110 // Treat protoless main() as nullary.
6111 if (isa<FunctionNoProtoType>(FT)) return;
6112
6113 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6114 unsigned nparams = FTP->getNumArgs();
6115 assert(FD->getNumParams() == nparams);
6116
John McCall0e21fcc2009-12-24 09:58:38 +00006117 bool HasExtraParameters = (nparams > 3);
6118
6119 // Darwin passes an undocumented fourth argument of type char**. If
6120 // other platforms start sprouting these, the logic below will start
6121 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00006122 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00006123 HasExtraParameters = false;
6124
6125 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00006126 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6127 FD->setInvalidDecl(true);
6128 nparams = 3;
6129 }
6130
6131 // FIXME: a lot of the following diagnostics would be improved
6132 // if we had some location information about types.
6133
6134 QualType CharPP =
6135 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00006136 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00006137
6138 for (unsigned i = 0; i < nparams; ++i) {
6139 QualType AT = FTP->getArgType(i);
6140
6141 bool mismatch = true;
6142
6143 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6144 mismatch = false;
6145 else if (Expected[i] == CharPP) {
6146 // As an extension, the following forms are okay:
6147 // char const **
6148 // char const * const *
6149 // char * const *
6150
John McCall8ccfcb52009-09-24 19:53:00 +00006151 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00006152 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006153 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6154 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00006155 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6156 qs.removeConst();
6157 mismatch = !qs.empty();
6158 }
6159 }
6160
6161 if (mismatch) {
6162 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6163 // TODO: suggest replacing given type with expected type
6164 FD->setInvalidDecl(true);
6165 }
6166 }
6167
6168 if (nparams == 1 && !FD->isInvalidDecl()) {
6169 Diag(FD->getLocation(), diag::warn_main_one_arg);
6170 }
Douglas Gregorbff62032010-10-21 16:57:46 +00006171
6172 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6173 Diag(FD->getLocation(), diag::err_main_template_decl);
6174 FD->setInvalidDecl();
6175 }
John McCalld9baf6a2009-07-24 03:03:21 +00006176}
6177
Eli Friedmand5a55bd2008-05-20 13:48:25 +00006178bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00006179 // FIXME: Need strict checking. In C89, we need to check for
6180 // any assignment, increment, decrement, function-calls, or
6181 // commas outside of a sizeof. In C99, it's the same list,
6182 // except that the aforementioned are allowed in unevaluated
6183 // expressions. Everything else falls under the
6184 // "may accept other forms of constant expressions" exception.
6185 // (We never end up here for C++, so the constant expression
6186 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00006187 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00006188 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00006189 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6190 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00006191 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00006192}
6193
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006194namespace {
6195 // Visits an initialization expression to see if OrigDecl is evaluated in
6196 // its own initialization and throws a warning if it does.
6197 class SelfReferenceChecker
6198 : public EvaluatedExprVisitor<SelfReferenceChecker> {
6199 Sema &S;
6200 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006201 bool isRecordType;
6202 bool isPODType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006203
6204 public:
6205 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6206
6207 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00006208 S(S), OrigDecl(OrigDecl) {
6209 isPODType = false;
6210 isRecordType = false;
6211 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6212 isPODType = VD->getType().isPODType(S.Context);
6213 isRecordType = VD->getType()->isRecordType();
6214 }
6215 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006216
Richard Trieu64c51ab2012-05-09 00:21:34 +00006217 // Sometimes, the expression passed in lacks the casts that are used
6218 // to determine which DeclRefExpr's to check. Assume that the casts
6219 // are present and continue visiting the expression.
6220 void HandleExpr(Expr *E) {
6221 // Skip checking T a = a where T is not a record type. Doing so is a
6222 // way to silence uninitialized warnings.
6223 if (isRecordType)
6224 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Trieua04ad1a2011-09-01 21:44:13 +00006225 HandleDeclRefExpr(DRE);
Richard Trieu64c51ab2012-05-09 00:21:34 +00006226
6227 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6228 HandleValue(CO->getTrueExpr());
6229 HandleValue(CO->getFalseExpr());
Richard Trieua04ad1a2011-09-01 21:44:13 +00006230 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00006231
6232 Visit(E);
6233 }
6234
6235 // For most expressions, the cast is directly above the DeclRefExpr.
6236 // For conditional operators, the cast can be outside the conditional
6237 // operator if both expressions are DeclRefExpr's.
6238 void HandleValue(Expr *E) {
6239 E = E->IgnoreParenImpCasts();
6240 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
6241 HandleDeclRefExpr(DRE);
6242 return;
6243 }
6244
6245 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6246 HandleValue(CO->getTrueExpr());
6247 HandleValue(CO->getFalseExpr());
6248 }
6249 }
6250
6251 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6252 if ((!isRecordType && E->getCastKind() == CK_LValueToRValue) ||
6253 (isRecordType && E->getCastKind() == CK_NoOp))
6254 HandleValue(E->getSubExpr());
6255
6256 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006257 }
6258
Richard Trieua04ad1a2011-09-01 21:44:13 +00006259 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00006260 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00006261 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00006262
Richard Trieu978dfc02012-03-08 01:15:31 +00006263 ValueDecl *VD = E->getMemberDecl();
Richard Trieu64c51ab2012-05-09 00:21:34 +00006264 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
6265 if (isa<FieldDecl>(VD) || (MD && !MD->isStatic()))
Richard Trieua04ad1a2011-09-01 21:44:13 +00006266 if (DeclRefExpr *DRE
6267 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6268 HandleDeclRefExpr(DRE);
6269 return;
6270 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00006271
Richard Trieu64c51ab2012-05-09 00:21:34 +00006272 Inherited::VisitMemberExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006273 }
6274
Richard Trieua04ad1a2011-09-01 21:44:13 +00006275 void VisitUnaryOperator(UnaryOperator *E) {
6276 // For POD record types, addresses of its own members are well-defined.
Richard Trieu64c51ab2012-05-09 00:21:34 +00006277 if (E->getOpcode() == UO_AddrOf && isRecordType && isPODType &&
Joerg Sonnenberger5c98e1f2012-06-17 23:10:39 +00006278 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) return;
Richard Trieua04ad1a2011-09-01 21:44:13 +00006279 Inherited::VisitUnaryOperator(E);
6280 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00006281
6282 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
6283
Richard Trieua04ad1a2011-09-01 21:44:13 +00006284 void HandleDeclRefExpr(DeclRefExpr *DRE) {
6285 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006286 if (OrigDecl != ReferenceDecl) return;
6287 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6288 Sema::NotForRedeclaration);
Richard Trieua04ad1a2011-09-01 21:44:13 +00006289 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006290 S.PDiag(diag::warn_uninit_self_reference_in_init)
Richard Trieua04ad1a2011-09-01 21:44:13 +00006291 << Result.getLookupName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006292 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00006293 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00006294 }
6295 };
6296}
6297
Richard Trieua04ad1a2011-09-01 21:44:13 +00006298/// CheckSelfReference - Warns if OrigDecl is used in expression E.
6299void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00006300 SelfReferenceChecker(*this, OrigDecl).HandleExpr(E);
Richard Trieua04ad1a2011-09-01 21:44:13 +00006301}
6302
Douglas Gregor5fb53972009-01-14 15:45:31 +00006303/// AddInitializerToDecl - Adds the initializer Init to the
6304/// declaration dcl. If DirectInit is true, this is C++ direct
6305/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00006306void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6307 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00006308 // If there is no declaration, there was an error parsing it. Just ignore
6309 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00006310 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00006311 return;
Mike Stump11289f42009-09-09 15:08:12 +00006312
Douglas Gregor0c880302009-03-11 23:00:04 +00006313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6314 // With declarators parsed the way they are, the parser cannot
6315 // distinguish between a normal initializer and a pure-specifier.
6316 // Thus this grotesque test.
6317 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00006318 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00006319 Context.getCanonicalType(IL->getType()) == Context.IntTy)
6320 CheckPureMethod(Method, Init->getSourceRange());
6321 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00006322 Diag(Method->getLocation(), diag::err_member_function_initialization)
6323 << Method->getDeclName() << Init->getSourceRange();
6324 Method->setInvalidDecl();
6325 }
6326 return;
6327 }
6328
Steve Naroff437b4d82007-09-12 20:13:48 +00006329 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6330 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00006331 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6332 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00006333 RealDecl->setInvalidDecl();
6334 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00006335 }
6336
Sebastian Redla9351792012-02-11 23:51:47 +00006337 // Check for self-references within variable initializers.
6338 // Variables declared within a function/method body are handled
6339 // by a dataflow analysis.
6340 if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6341 CheckSelfReference(RealDecl, Init);
6342
6343 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6344
Richard Smith0cc85782011-12-15 19:20:59 +00006345 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith74801c82012-07-08 04:13:07 +00006346 AutoType *Auto = 0;
6347 if (TypeMayContainAuto &&
6348 (Auto = VDecl->getType()->getContainedAutoType()) &&
6349 !Auto->isDeduced()) {
Sebastian Redla9351792012-02-11 23:51:47 +00006350 Expr *DeduceInit = Init;
6351 // Initializer could be a C++ direct-initializer. Deduction only works if it
6352 // contains exactly one expression.
6353 if (CXXDirectInit) {
6354 if (CXXDirectInit->getNumExprs() == 0) {
6355 // It isn't possible to write this directly, but it is possible to
6356 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006357 Diag(CXXDirectInit->getLocStart(),
Sebastian Redla9351792012-02-11 23:51:47 +00006358 diag::err_auto_var_init_no_expression)
6359 << VDecl->getDeclName() << VDecl->getType()
6360 << VDecl->getSourceRange();
6361 RealDecl->setInvalidDecl();
6362 return;
6363 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006364 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Sebastian Redla9351792012-02-11 23:51:47 +00006365 diag::err_auto_var_init_multiple_expressions)
6366 << VDecl->getDeclName() << VDecl->getType()
6367 << VDecl->getSourceRange();
6368 RealDecl->setInvalidDecl();
6369 return;
6370 } else {
6371 DeduceInit = CXXDirectInit->getExpr(0);
6372 }
6373 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006374 TypeSourceInfo *DeducedType = 0;
Sebastian Redla9351792012-02-11 23:51:47 +00006375 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00006376 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00006377 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9647d3c2011-03-17 16:11:59 +00006378 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006379 RealDecl->setInvalidDecl();
6380 return;
6381 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006382 VDecl->setTypeSourceInfo(DeducedType);
6383 VDecl->setType(DeducedType->getType());
Douglas Gregord5c48442012-02-20 20:05:29 +00006384 VDecl->ClearLinkageCache();
6385
John McCall31168b02011-06-15 23:02:42 +00006386 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006387 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00006388 VDecl->setInvalidDecl();
6389
Jordan Rosed8d56692012-06-08 22:46:07 +00006390 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
6391 // 'id' instead of a specific object type prevents most of our usual checks.
6392 // We only want to warn outside of template instantiations, though:
6393 // inside a template, the 'id' could have come from a parameter.
6394 if (ActiveTemplateInstantiations.empty() &&
6395 DeducedType->getType()->isObjCIdType()) {
6396 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
6397 Diag(Loc, diag::warn_auto_var_is_id)
6398 << VDecl->getDeclName() << DeduceInit->getSourceRange();
6399 }
6400
Richard Smith30482bc2011-02-20 03:19:35 +00006401 // If this is a redeclaration, check that the type we just deduced matches
6402 // the previously declared type.
Douglas Gregorec9fd132012-01-14 16:38:05 +00006403 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith30482bc2011-02-20 03:19:35 +00006404 MergeVarDeclTypes(VDecl, Old);
6405 }
Richard Smith0cc85782011-12-15 19:20:59 +00006406
6407 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6408 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6409 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6410 VDecl->setInvalidDecl();
6411 return;
6412 }
6413
Sebastian Redla9351792012-02-11 23:51:47 +00006414 if (!VDecl->getType()->isDependentType()) {
6415 // A definition must end up with a complete type, which means it must be
6416 // complete with the restriction that an array type might be completed by
6417 // the initializer; note that later code assumes this restriction.
6418 QualType BaseDeclType = VDecl->getType();
6419 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6420 BaseDeclType = Array->getElementType();
6421 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6422 diag::err_typecheck_decl_incomplete_type)) {
6423 RealDecl->setInvalidDecl();
6424 return;
6425 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00006426
Sebastian Redla9351792012-02-11 23:51:47 +00006427 // The variable can not have an abstract class type.
6428 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6429 diag::err_abstract_type_in_decl,
6430 AbstractVariableType))
6431 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00006432 }
6433
Sebastian Redl5ca79842010-02-01 20:16:42 +00006434 const VarDecl *Def;
6435 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00006436 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00006437 << VDecl->getDeclName();
6438 Diag(Def->getLocation(), diag::note_previous_definition);
6439 VDecl->setInvalidDecl();
6440 return;
6441 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00006442
Douglas Gregorf0f83692010-08-24 05:27:49 +00006443 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006444 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00006445 // C++ [class.static.data]p4
6446 // If a static data member is of const integral or const
6447 // enumeration type, its declaration in the class definition can
6448 // specify a constant-initializer which shall be an integral
6449 // constant expression (5.19). In that case, the member can appear
6450 // in integral constant expressions. The member shall still be
6451 // defined in a namespace scope if it is used in the program and the
6452 // namespace scope definition shall not contain an initializer.
6453 //
6454 // We already performed a redefinition check above, but for static
6455 // data members we also need to check whether there was an in-class
6456 // declaration with an initializer.
6457 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikie30d15442011-10-19 22:56:21 +00006458 Diag(VDecl->getLocation(), diag::err_redefinition)
6459 << VDecl->getDeclName();
Douglas Gregor71f39c92010-12-16 01:31:22 +00006460 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6461 return;
6462 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00006463
Douglas Gregor71f39c92010-12-16 01:31:22 +00006464 if (VDecl->hasLocalStorage())
6465 getCurFunction()->setHasBranchProtectedScope();
6466
6467 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6468 VDecl->setInvalidDecl();
6469 return;
6470 }
6471 }
John McCalld4e1b762010-08-01 01:24:59 +00006472
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00006473 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6474 // a kernel function cannot be initialized."
6475 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6476 Diag(VDecl->getLocation(), diag::err_local_cant_init);
6477 VDecl->setInvalidDecl();
6478 return;
6479 }
6480
Steve Naroff61091402007-09-12 14:07:44 +00006481 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00006482 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00006483 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00006484
6485 // Top-level message sends default to 'id' when we're in a debugger
6486 // and we are assigning it to a variable of 'id' type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006487 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00006488 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6489 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6490 if (Result.isInvalid()) {
6491 VDecl->setInvalidDecl();
6492 return;
6493 }
6494 Init = Result.take();
6495 }
Richard Smith0cc85782011-12-15 19:20:59 +00006496
6497 // Perform the initialization.
6498 if (!VDecl->isInvalidDecl()) {
6499 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6500 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00006501 = DirectInit ?
6502 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6503 Init->getLocStart(),
6504 Init->getLocEnd())
6505 : InitializationKind::CreateDirectList(
6506 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00006507 : InitializationKind::CreateCopy(VDecl->getLocation(),
6508 Init->getLocStart());
6509
Sebastian Redla9351792012-02-11 23:51:47 +00006510 Expr **Args = &Init;
6511 unsigned NumArgs = 1;
6512 if (CXXDirectInit) {
6513 Args = CXXDirectInit->getExprs();
6514 NumArgs = CXXDirectInit->getNumExprs();
6515 }
6516 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
Richard Smith0cc85782011-12-15 19:20:59 +00006517 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redla9351792012-02-11 23:51:47 +00006518 MultiExprArg(*this, Args,NumArgs),
Richard Smith0cc85782011-12-15 19:20:59 +00006519 &DclT);
6520 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00006521 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00006522 return;
Steve Naroff61091402007-09-12 14:07:44 +00006523 }
Richard Smith0cc85782011-12-15 19:20:59 +00006524
6525 Init = Result.takeAs<Expr>();
6526 }
6527
6528 // If the type changed, it means we had an incomplete type that was
6529 // completed by the initializer. For example:
6530 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00006531 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00006532 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00006533 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00006534
6535 // Check any implicit conversions within the expression.
6536 CheckImplicitConversions(Init, VDecl->getLocation());
6537
6538 if (!VDecl->isInvalidDecl())
6539 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6540
6541 Init = MaybeCreateExprWithCleanups(Init);
6542 // Attach the initializer to the decl.
6543 VDecl->setInit(Init);
6544
6545 if (VDecl->isLocalVarDecl()) {
6546 // C99 6.7.8p4: All the expressions in an initializer for an object that has
6547 // static storage duration shall be constant expressions or string literals.
6548 // C++ does not have this restriction.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006549 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
Richard Smith0cc85782011-12-15 19:20:59 +00006550 VDecl->getStorageClass() == SC_Static)
6551 CheckForConstantInitializer(Init, DclT);
Mike Stump11289f42009-09-09 15:08:12 +00006552 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00006553 VDecl->getLexicalDeclContext()->isRecord()) {
6554 // This is an in-class initialization for a static data member, e.g.,
6555 //
6556 // struct S {
6557 // static const int value = 17;
6558 // };
6559
Douglas Gregor0c880302009-03-11 23:00:04 +00006560 // C++ [class.mem]p4:
6561 // A member-declarator can contain a constant-initializer only
6562 // if it declares a static member (9.4) of const integral or
6563 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00006564 //
Richard Smith0cc85782011-12-15 19:20:59 +00006565 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00006566 // If a non-volatile const static data member is of integral or
6567 // enumeration type, its declaration in the class definition can
6568 // specify a brace-or-equal-initializer in which every initalizer-clause
6569 // that is an assignment-expression is a constant expression. A static
6570 // data member of literal type can be declared in the class definition
6571 // with the constexpr specifier; if so, its declaration shall specify a
6572 // brace-or-equal-initializer in which every initializer-clause that is
6573 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00006574
6575 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00006576 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00006577
Richard Smith2316cd82011-09-29 19:11:37 +00006578 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00006579 // type. We separately check that every constexpr variable is of literal
6580 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00006581 } else if (VDecl->isConstexpr()) {
6582
John McCalldb768922010-09-10 23:21:22 +00006583 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00006584 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00006585 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6586 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00006587 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00006588
6589 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00006590 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00006591 // Check whether the expression is a constant expression.
6592 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006593 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00006594 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00006595 // in-class initializer cannot be volatile.
6596 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6597 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00006598 ; // Nothing to check.
6599 else if (Init->isIntegerConstantExpr(Context, &Loc))
6600 ; // Ok, it's an ICE!
6601 else if (Init->isEvaluatable(Context)) {
6602 // If we can constant fold the initializer through heroics, accept it,
6603 // but report this as a use of an extension for -pedantic.
6604 Diag(Loc, diag::ext_in_class_initializer_non_constant)
6605 << Init->getSourceRange();
6606 } else {
6607 // Otherwise, this is some crazy unknown case. Report the issue at the
6608 // location provided by the isIntegerConstantExpr failed check.
6609 Diag(Loc, diag::err_in_class_initializer_non_constant)
6610 << Init->getSourceRange();
6611 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00006612 }
6613
Richard Smith0cc85782011-12-15 19:20:59 +00006614 // We allow foldable floating-point constants as an extension.
6615 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smith2316cd82011-09-29 19:11:37 +00006616 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006617 << DclT << Init->getSourceRange();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006618 if (getLangOpts().CPlusPlus0x)
Richard Smith7b729cd2011-09-30 00:33:19 +00006619 Diag(VDecl->getLocation(),
6620 diag::note_in_class_initializer_float_type_constexpr)
6621 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
John McCalldb768922010-09-10 23:21:22 +00006622
Richard Smith0cc85782011-12-15 19:20:59 +00006623 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
John McCalldb768922010-09-10 23:21:22 +00006624 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6625 << Init->getSourceRange();
6626 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00006627 }
Richard Smith256336d2011-09-29 23:18:34 +00006628
Richard Smith0cc85782011-12-15 19:20:59 +00006629 // Suggest adding 'constexpr' in C++11 for literal types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006630 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
Richard Smith256336d2011-09-29 23:18:34 +00006631 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006632 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00006633 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6634 VDecl->setConstexpr(true);
6635
Richard Smith2316cd82011-09-29 19:11:37 +00006636 } else {
6637 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00006638 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00006639 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00006640 }
Steve Naroff08899ff2008-04-15 22:42:06 +00006641 } else if (VDecl->isFileVarDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00006642 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006643 (!getLangOpts().CPlusPlus ||
Douglas Gregorfceea362010-04-22 14:36:26 +00006644 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00006645 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00006646
Richard Smith0cc85782011-12-15 19:20:59 +00006647 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006648 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00006649 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00006650 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00006651
Sebastian Redla9351792012-02-11 23:51:47 +00006652 // We will represent direct-initialization similarly to copy-initialization:
6653 // int x(1); -as-> int x = 1;
6654 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6655 //
6656 // Clients that want to distinguish between the two forms, can check for
6657 // direct initializer using VarDecl::getInitStyle().
6658 // A major benefit is that clients that don't particularly care about which
6659 // exactly form was it (like the CodeGen) can handle both cases without
6660 // special case code.
6661
6662 // C++ 8.5p11:
6663 // The form of initialization (using parentheses or '=') is generally
6664 // insignificant, but does matter when the entity being initialized has a
6665 // class type.
6666 if (CXXDirectInit) {
6667 assert(DirectInit && "Call-style initializer must be direct init.");
6668 VDecl->setInitStyle(VarDecl::CallInit);
6669 } else if (DirectInit) {
6670 // This must be list-initialization. No other way is direct-initialization.
6671 VDecl->setInitStyle(VarDecl::ListInit);
6672 }
6673
John McCall8b7fd8f12011-01-19 11:48:09 +00006674 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00006675}
6676
John McCalleae5acb2010-03-31 02:13:20 +00006677/// ActOnInitializerError - Given that there was an error parsing an
6678/// initializer for the given declaration, try to return to some form
6679/// of sanity.
John McCall48871652010-08-21 09:40:31 +00006680void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00006681 // Our main concern here is re-establishing invariants like "a
6682 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00006683 if (!D || D->isInvalidDecl()) return;
6684
6685 VarDecl *VD = dyn_cast<VarDecl>(D);
6686 if (!VD) return;
6687
Richard Smith30482bc2011-02-20 03:19:35 +00006688 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00006689 if (ParsingInitForAutoVars.count(D)) {
6690 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00006691 return;
6692 }
6693
John McCalleae5acb2010-03-31 02:13:20 +00006694 QualType Ty = VD->getType();
6695 if (Ty->isDependentType()) return;
6696
6697 // Require a complete type.
6698 if (RequireCompleteType(VD->getLocation(),
6699 Context.getBaseElementType(Ty),
6700 diag::err_typecheck_decl_incomplete_type)) {
6701 VD->setInvalidDecl();
6702 return;
6703 }
6704
6705 // Require an abstract type.
6706 if (RequireNonAbstractType(VD->getLocation(), Ty,
6707 diag::err_abstract_type_in_decl,
6708 AbstractVariableType)) {
6709 VD->setInvalidDecl();
6710 return;
6711 }
6712
6713 // Don't bother complaining about constructors or destructors,
6714 // though.
6715}
6716
John McCall48871652010-08-21 09:40:31 +00006717void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00006718 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00006719 // If there is no declaration, there was an error parsing it. Just ignore it.
6720 if (RealDecl == 0)
6721 return;
6722
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006723 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6724 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00006725
Richard Smithf0215fe2011-12-25 21:17:58 +00006726 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00006727 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00006728 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6729 << Var->getDeclName() << Type;
6730 Var->setInvalidDecl();
6731 return;
6732 }
Mike Stump11289f42009-09-09 15:08:12 +00006733
Richard Smithf0215fe2011-12-25 21:17:58 +00006734 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00006735 // the constexpr specifier; if so, its declaration shall specify
6736 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00006737 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6738 // the definition of a variable [...] or the declaration of a static data
6739 // member.
6740 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6741 if (Var->isStaticDataMember())
6742 Diag(Var->getLocation(),
6743 diag::err_constexpr_static_mem_var_requires_init)
6744 << Var->getDeclName();
6745 else
6746 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00006747 Var->setInvalidDecl();
6748 return;
6749 }
6750
Douglas Gregore6565622010-02-09 07:26:29 +00006751 switch (Var->isThisDeclarationADefinition()) {
6752 case VarDecl::Definition:
6753 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6754 break;
6755
6756 // We have an out-of-line definition of a static data member
6757 // that has an in-class initializer, so we type-check this like
6758 // a declaration.
6759 //
6760 // Fall through
6761
6762 case VarDecl::DeclarationOnly:
6763 // It's only a declaration.
6764
6765 // Block scope. C99 6.7p7: If an identifier for an object is
6766 // declared with no linkage (C99 6.2.2p6), the type for the
6767 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00006768 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00006769 !Var->getLinkage() && !Var->isInvalidDecl() &&
6770 RequireCompleteType(Var->getLocation(), Type,
6771 diag::err_typecheck_decl_incomplete_type))
6772 Var->setInvalidDecl();
6773
6774 // Make sure that the type is not abstract.
6775 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6776 RequireNonAbstractType(Var->getLocation(), Type,
6777 diag::err_abstract_type_in_decl,
6778 AbstractVariableType))
6779 Var->setInvalidDecl();
6780 return;
6781
6782 case VarDecl::TentativeDefinition:
6783 // File scope. C99 6.9.2p2: A declaration of an identifier for an
6784 // object that has file scope without an initializer, and without a
6785 // storage-class specifier or with the storage-class specifier "static",
6786 // constitutes a tentative definition. Note: A tentative definition with
6787 // external linkage is valid (C99 6.2.2p5).
6788 if (!Var->isInvalidDecl()) {
6789 if (const IncompleteArrayType *ArrayT
6790 = Context.getAsIncompleteArrayType(Type)) {
6791 if (RequireCompleteType(Var->getLocation(),
6792 ArrayT->getElementType(),
6793 diag::err_illegal_decl_array_incomplete_type))
6794 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00006795 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00006796 // C99 6.9.2p3: If the declaration of an identifier for an object is
6797 // a tentative definition and has internal linkage (C99 6.2.2p3), the
6798 // declared type shall not be an incomplete type.
6799 // NOTE: code such as the following
6800 // static struct s;
6801 // struct s { int a; };
6802 // is accepted by gcc. Hence here we issue a warning instead of
6803 // an error and we do not invalidate the static declaration.
6804 // NOTE: to avoid multiple warnings, only check the first declaration.
Douglas Gregorec9fd132012-01-14 16:38:05 +00006805 if (Var->getPreviousDecl() == 0)
Douglas Gregore6565622010-02-09 07:26:29 +00006806 RequireCompleteType(Var->getLocation(), Type,
6807 diag::ext_typecheck_decl_incomplete_type);
6808 }
6809 }
6810
6811 // Record the tentative definition; we're done.
6812 if (!Var->isInvalidDecl())
6813 TentativeDefinitions.push_back(Var);
6814 return;
6815 }
6816
6817 // Provide a specific diagnostic for uninitialized variable
6818 // definitions with incomplete array type.
6819 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00006820 Diag(Var->getLocation(),
6821 diag::err_typecheck_incomplete_array_needs_initializer);
6822 Var->setInvalidDecl();
6823 return;
6824 }
6825
John McCalla755f0f2010-08-01 01:25:24 +00006826 // Provide a specific diagnostic for uninitialized variable
6827 // definitions with reference type.
6828 if (Type->isReferenceType()) {
6829 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6830 << Var->getDeclName()
6831 << SourceRange(Var->getLocation(), Var->getLocation());
6832 Var->setInvalidDecl();
6833 return;
6834 }
Douglas Gregore6565622010-02-09 07:26:29 +00006835
6836 // Do not attempt to type-check the default initializer for a
6837 // variable with dependent type.
6838 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00006839 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006840
Douglas Gregore6565622010-02-09 07:26:29 +00006841 if (Var->isInvalidDecl())
6842 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00006843
Douglas Gregore6565622010-02-09 07:26:29 +00006844 if (RequireCompleteType(Var->getLocation(),
6845 Context.getBaseElementType(Type),
6846 diag::err_typecheck_decl_incomplete_type)) {
6847 Var->setInvalidDecl();
6848 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006849 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006850
Douglas Gregore6565622010-02-09 07:26:29 +00006851 // The variable can not have an abstract class type.
6852 if (RequireNonAbstractType(Var->getLocation(), Type,
6853 diag::err_abstract_type_in_decl,
6854 AbstractVariableType)) {
6855 Var->setInvalidDecl();
6856 return;
6857 }
6858
Douglas Gregor9574af62011-05-21 17:52:48 +00006859 // Check for jumps past the implicit initializer. C++0x
6860 // clarifies that this applies to a "variable with automatic
6861 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00006862 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00006863 // A program that jumps from a point where a variable with automatic
6864 // storage duration is not in scope to a point where it is in scope is
6865 // ill-formed unless the variable has scalar type, class type with a
6866 // trivial default constructor and a trivial destructor, a cv-qualified
6867 // version of one of these types, or an array of one of the preceding
6868 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006869 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00006870 if (const RecordType *Record
6871 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00006872 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00006873 // Mark the function for further checking even if the looser rules of
6874 // C++11 do not require such checks, so that we can diagnose
6875 // incompatibilities with C++98.
6876 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00006877 getCurFunction()->setHasBranchProtectedScope();
6878 }
Douglas Gregore6565622010-02-09 07:26:29 +00006879 }
Douglas Gregor9574af62011-05-21 17:52:48 +00006880
6881 // C++03 [dcl.init]p9:
6882 // If no initializer is specified for an object, and the
6883 // object is of (possibly cv-qualified) non-POD class type (or
6884 // array thereof), the object shall be default-initialized; if
6885 // the object is of const-qualified type, the underlying class
6886 // type shall have a user-declared default
6887 // constructor. Otherwise, if no initializer is specified for
6888 // a non- static object, the object and its subobjects, if
6889 // any, have an indeterminate initial value); if the object
6890 // or any of its subobjects are of const-qualified type, the
6891 // program is ill-formed.
6892 // C++0x [dcl.init]p11:
6893 // If no initializer is specified for an object, the object is
6894 // default-initialized; [...].
6895 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6896 InitializationKind Kind
6897 = InitializationKind::CreateDefault(Var->getLocation());
6898
6899 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6900 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6901 MultiExprArg(*this, 0, 0));
6902 if (Init.isInvalid())
6903 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00006904 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00006905 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00006906 // This is important for template substitution.
6907 Var->setInitStyle(VarDecl::CallInit);
6908 }
Douglas Gregor589973b2010-03-08 02:45:10 +00006909
John McCall8b7fd8f12011-01-19 11:48:09 +00006910 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006911 }
6912}
6913
Richard Smith02e85f32011-04-14 22:09:26 +00006914void Sema::ActOnCXXForRangeDecl(Decl *D) {
6915 VarDecl *VD = dyn_cast<VarDecl>(D);
6916 if (!VD) {
6917 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6918 D->setInvalidDecl();
6919 return;
6920 }
6921
6922 VD->setCXXForRangeDecl(true);
6923
6924 // for-range-declaration cannot be given a storage class specifier.
6925 int Error = -1;
6926 switch (VD->getStorageClassAsWritten()) {
6927 case SC_None:
6928 break;
6929 case SC_Extern:
6930 Error = 0;
6931 break;
6932 case SC_Static:
6933 Error = 1;
6934 break;
6935 case SC_PrivateExtern:
6936 Error = 2;
6937 break;
6938 case SC_Auto:
6939 Error = 3;
6940 break;
6941 case SC_Register:
6942 Error = 4;
6943 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00006944 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00006945 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00006946 }
Richard Smith2316cd82011-09-29 19:11:37 +00006947 if (VD->isConstexpr())
6948 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00006949 if (Error != -1) {
6950 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6951 << VD->getDeclName() << Error;
6952 D->setInvalidDecl();
6953 }
6954}
6955
John McCall8b7fd8f12011-01-19 11:48:09 +00006956void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6957 if (var->isInvalidDecl()) return;
6958
John McCall31168b02011-06-15 23:02:42 +00006959 // In ARC, don't allow jumps past the implicit initialization of a
6960 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006961 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006962 var->hasLocalStorage()) {
6963 switch (var->getType().getObjCLifetime()) {
6964 case Qualifiers::OCL_None:
6965 case Qualifiers::OCL_ExplicitNone:
6966 case Qualifiers::OCL_Autoreleasing:
6967 break;
6968
6969 case Qualifiers::OCL_Weak:
6970 case Qualifiers::OCL_Strong:
6971 getCurFunction()->setHasBranchProtectedScope();
6972 break;
6973 }
6974 }
6975
John McCall8b7fd8f12011-01-19 11:48:09 +00006976 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006977 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00006978
6979 QualType baseType = Context.getBaseElementType(var->getType());
6980 if (baseType->isDependentType()) return;
6981
6982 // __block variables might require us to capture a copy-initializer.
6983 if (var->hasAttr<BlocksAttr>()) {
6984 // It's currently invalid to ever have a __block variable with an
6985 // array type; should we diagnose that here?
6986
6987 // Regardless, we don't want to ignore array nesting when
6988 // constructing this copy.
6989 QualType type = var->getType();
6990
6991 if (type->isStructureOrClassType()) {
6992 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00006993 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
John McCall8b7fd8f12011-01-19 11:48:09 +00006994 ExprResult result =
6995 PerformCopyInitialization(
6996 InitializedEntity::InitializeBlock(poi, type, false),
6997 poi, Owned(varRef));
6998 if (!result.isInvalid()) {
6999 result = MaybeCreateExprWithCleanups(result);
7000 Expr *init = result.takeAs<Expr>();
7001 Context.setBlockVarCopyInits(var, init);
7002 }
7003 }
7004 }
7005
Richard Smitheda3c842011-11-07 22:16:17 +00007006 Expr *Init = var->getInit();
7007 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
7008
Richard Smithd0b4dd62011-12-19 06:19:21 +00007009 if (!var->getDeclContext()->isDependentContext() && Init) {
7010 if (IsGlobal && !var->isConstexpr() &&
7011 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7012 var->getLocation())
7013 != DiagnosticsEngine::Ignored &&
7014 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
Richard Smitheda3c842011-11-07 22:16:17 +00007015 Diag(var->getLocation(), diag::warn_global_constructor)
7016 << Init->getSourceRange();
Richard Smithd0b4dd62011-12-19 06:19:21 +00007017
Richard Smithd0b4dd62011-12-19 06:19:21 +00007018 if (var->isConstexpr()) {
7019 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
7020 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7021 SourceLocation DiagLoc = var->getLocation();
7022 // If the note doesn't add any useful information other than a source
7023 // location, fold it into the primary diagnostic.
7024 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7025 diag::note_invalid_subexpr_in_const_expr) {
7026 DiagLoc = Notes[0].first;
7027 Notes.clear();
7028 }
7029 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7030 << var << Init->getSourceRange();
7031 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7032 Diag(Notes[I].first, Notes[I].second);
7033 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00007034 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00007035 // Check whether the initializer of a const variable of integral or
7036 // enumeration type is an ICE now, since we can't tell whether it was
7037 // initialized by a constant expression if we check later.
7038 var->checkInitIsICE();
7039 }
Richard Smitheda3c842011-11-07 22:16:17 +00007040 }
John McCall8b7fd8f12011-01-19 11:48:09 +00007041
7042 // Require the destructor.
7043 if (const RecordType *recordType = baseType->getAs<RecordType>())
7044 FinalizeVarWithDestructor(var, recordType);
7045}
7046
Richard Smithb2bc2e62011-02-21 20:05:19 +00007047/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7048/// any semantic actions necessary after any initializer has been attached.
7049void
7050Sema::FinalizeDeclaration(Decl *ThisDecl) {
7051 // Note that we are no longer parsing the initializer for this declaration.
7052 ParsingInitForAutoVars.erase(ThisDecl);
7053}
7054
John McCallba7bf592010-08-24 05:47:05 +00007055Sema::DeclGroupPtrTy
7056Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
7057 Decl **Group, unsigned NumDecls) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007058 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00007059
7060 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00007061 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00007062
Richard Smith2abf6762011-02-23 00:37:57 +00007063 for (unsigned i = 0; i != NumDecls; ++i)
7064 if (Decl *D = Group[i])
7065 Decls.push_back(D);
7066
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007067 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00007068 DS.getTypeSpecType() == DeclSpec::TST_auto);
7069}
7070
7071/// BuildDeclaratorGroup - convert a list of declarations into a declaration
7072/// group, performing any necessary semantic checking.
7073Sema::DeclGroupPtrTy
7074Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
7075 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00007076 // C++0x [dcl.spec.auto]p7:
7077 // If the type deduced for the template parameter U is not the same in each
7078 // deduction, the program is ill-formed.
7079 // FIXME: When initializer-list support is added, a distinction is needed
7080 // between the deduced type U and the deduced type which 'auto' stands for.
7081 // auto a = 0, b = { 1, 2, 3 };
7082 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00007083 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00007084 QualType Deduced;
7085 CanQualType DeducedCanon;
7086 VarDecl *DeducedDecl = 0;
7087 for (unsigned i = 0; i != NumDecls; ++i) {
7088 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
7089 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00007090 // Don't reissue diagnostics when instantiating a template.
7091 if (AT && D->isInvalidDecl())
7092 break;
Richard Smith30482bc2011-02-20 03:19:35 +00007093 if (AT && AT->isDeduced()) {
7094 QualType U = AT->getDeducedType();
7095 CanQualType UCanon = Context.getCanonicalType(U);
7096 if (Deduced.isNull()) {
7097 Deduced = U;
7098 DeducedCanon = UCanon;
7099 DeducedDecl = D;
7100 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00007101 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
7102 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00007103 << Deduced << DeducedDecl->getDeclName()
7104 << U << D->getDeclName()
7105 << DeducedDecl->getInit()->getSourceRange()
7106 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00007107 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00007108 break;
7109 }
7110 }
7111 }
7112 }
7113 }
7114
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007115 ActOnDocumentableDecls(Group, NumDecls);
7116
Richard Smith2abf6762011-02-23 00:37:57 +00007117 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00007118}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00007119
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007120void Sema::ActOnDocumentableDecl(Decl *D) {
7121 ActOnDocumentableDecls(&D, 1);
7122}
7123
7124void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
7125 // Don't parse the comment if Doxygen diagnostics are ignored.
7126 if (NumDecls == 0 || !Group[0])
7127 return;
7128
7129 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
7130 Group[0]->getLocation())
7131 == DiagnosticsEngine::Ignored)
7132 return;
7133
7134 if (NumDecls >= 2) {
7135 // This is a decl group. Normally it will contain only declarations
7136 // procuded from declarator list. But in case we have any definitions or
7137 // additional declaration references:
7138 // 'typedef struct S {} S;'
7139 // 'typedef struct S *S;'
7140 // 'struct S *pS;'
7141 // FinalizeDeclaratorGroup adds these as separate declarations.
7142 Decl *MaybeTagDecl = Group[0];
7143 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
7144 Group++;
7145 NumDecls--;
7146 }
7147 }
7148
7149 // See if there are any new comments that are not attached to a decl.
7150 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
7151 if (!Comments.empty() &&
7152 !Comments.back()->isAttached()) {
7153 // There is at least one comment that not attached to a decl.
7154 // Maybe it should be attached to one of these decls?
7155 //
7156 // Note that this way we pick up not only comments that precede the
7157 // declaration, but also comments that *follow* the declaration -- thanks to
7158 // the lookahead in the lexer: we've consumed the semicolon and looked
7159 // ahead through comments.
7160 for (unsigned i = 0; i != NumDecls; ++i)
7161 Context.getCommentForDecl(Group[i]);
7162 }
7163}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00007164
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007165/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
7166/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00007167Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00007168 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00007169
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007170 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Peter Collingbourne99eddc32011-10-21 11:55:09 +00007171 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00007172 VarDecl::StorageClass StorageClass = SC_None;
7173 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00007174 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00007175 StorageClass = SC_Register;
7176 StorageClassAsWritten = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007177 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00007178 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
7179 StorageClass = SC_Auto;
7180 StorageClassAsWritten = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00007181 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007182 Diag(DS.getStorageClassSpecLoc(),
7183 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00007184 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007185 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007186
7187 if (D.getDeclSpec().isThreadSpecified())
7188 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00007189 if (D.getDeclSpec().isConstexprSpecified())
7190 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
7191 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007192
Eli Friedman574c7452009-04-07 19:37:57 +00007193 DiagnoseFunctionSpecifiers(D);
7194
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00007195 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00007196 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00007197
David Blaikiebbafb8a2012-03-11 07:00:24 +00007198 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00007199 // Check that there are no default arguments inside the type of this
7200 // parameter.
7201 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00007202
7203 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
7204 if (D.getCXXScopeSpec().isSet()) {
7205 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
7206 << D.getCXXScopeSpec().getRange();
7207 D.getCXXScopeSpec().clear();
7208 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00007209 }
7210
Alexis Hunta56cbcc2010-11-03 01:07:06 +00007211 // Ensure we have a valid name
7212 IdentifierInfo *II = 0;
7213 if (D.hasName()) {
7214 II = D.getIdentifier();
7215 if (!II) {
7216 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7217 << GetNameForDeclarator(D).getName().getAsString();
7218 D.setInvalidType(true);
7219 }
7220 }
7221
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00007222 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00007223 if (II) {
John McCall84f02672010-03-18 06:42:38 +00007224 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7225 ForRedeclaration);
7226 LookupName(R, S);
7227 if (R.isSingleResult()) {
7228 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00007229 if (PrevDecl->isTemplateParameter()) {
7230 // Maybe we will complain about the shadowed template parameter.
7231 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7232 // Just pretend that we didn't see the previous declaration.
7233 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00007234 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00007235 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00007236 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007237
Chris Lattnerd9773512009-01-21 02:38:50 +00007238 // Recover by removing the name
7239 II = 0;
7240 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007241 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00007242 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007243 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00007244 }
Steve Naroff773df5c2007-08-07 22:44:21 +00007245
John McCallf7b2fb52010-01-22 00:28:27 +00007246 // Temporarily put parameter variables in the translation unit, not
7247 // the enclosing context. This prevents them from accidentally
7248 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00007249 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007250 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00007251 D.getIdentifierLoc(), II,
7252 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007253 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00007254
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007255 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00007256 New->setInvalidDecl();
7257
7258 assert(S->isFunctionPrototypeScope());
7259 assert(S->getFunctionPrototypeDepth() >= 1);
7260 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7261 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00007262
Douglas Gregor91f84212008-12-11 16:49:14 +00007263 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00007264 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00007265 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00007266 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00007267
Douglas Gregor758a8692009-06-17 21:51:59 +00007268 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00007269
Douglas Gregor41866812011-09-12 18:37:38 +00007270 if (D.getDeclSpec().isModulePrivateSpecified())
7271 Diag(New->getLocation(), diag::err_module_private_local)
7272 << 1 << New->getDeclName()
7273 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7274 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7275
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007276 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00007277 Diag(New->getLocation(), diag::err_block_on_nonlocal);
7278 }
John McCall48871652010-08-21 09:40:31 +00007279 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00007280}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00007281
John McCalla3ccba02010-06-04 11:21:44 +00007282/// \brief Synthesizes a variable for a parameter arising from a
7283/// typedef.
7284ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7285 SourceLocation Loc,
7286 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007287 /* FIXME: setting StartLoc == Loc.
7288 Would it be worth to modify callers so as to provide proper source
7289 location for the unnamed parameters, embedding the parameter's type? */
7290 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00007291 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007292 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00007293 Param->setImplicit();
7294 return Param;
7295}
7296
John McCallc5990642010-08-24 09:05:15 +00007297void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7298 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00007299 // Don't diagnose unused-parameter errors in template instantiations; we
7300 // will already have done so in the template itself.
7301 if (!ActiveTemplateInstantiations.empty())
7302 return;
7303
7304 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00007305 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00007306 !(*Param)->hasAttr<UnusedAttr>()) {
7307 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7308 << (*Param)->getDeclName();
7309 }
7310 }
7311}
7312
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007313void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7314 ParmVarDecl * const *ParamEnd,
7315 QualType ReturnTy,
7316 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007317 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007318 return;
7319
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007320 // Warn if the return value is pass-by-value and larger than the specified
7321 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00007322 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007323 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007324 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007325 Diag(D->getLocation(), diag::warn_return_value_size)
7326 << D->getDeclName() << Size;
7327 }
7328
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007329 // Warn if any parameter is pass-by-value and larger than the specified
7330 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007331 for (; Param != ParamEnd; ++Param) {
7332 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00007333 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007334 continue;
7335 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00007336 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007337 Diag((*Param)->getLocation(), diag::warn_parameter_size)
7338 << (*Param)->getDeclName() << Size;
7339 }
7340}
7341
Abramo Bagnaradff19302011-03-08 08:55:46 +00007342ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7343 SourceLocation NameLoc, IdentifierInfo *Name,
7344 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007345 VarDecl::StorageClass StorageClass,
7346 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00007347 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007348 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00007349 T.getObjCLifetime() == Qualifiers::OCL_None &&
7350 T->isObjCLifetimeType()) {
7351
7352 Qualifiers::ObjCLifetime lifetime;
7353
7354 // Special cases for arrays:
7355 // - if it's const, use __unsafe_unretained
7356 // - otherwise, it's an error
7357 if (T->isArrayType()) {
7358 if (!T.isConstQualified()) {
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00007359 DelayedDiagnostics.add(
7360 sema::DelayedDiagnostic::makeForbiddenType(
7361 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
John McCall31168b02011-06-15 23:02:42 +00007362 }
7363 lifetime = Qualifiers::OCL_ExplicitNone;
7364 } else {
7365 lifetime = T->getObjCARCImplicitLifetime();
7366 }
7367 T = Context.getLifetimeQualifiedType(T, lifetime);
7368 }
7369
Abramo Bagnaradff19302011-03-08 08:55:46 +00007370 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00007371 Context.getAdjustedParameterType(T),
7372 TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00007373 StorageClass, StorageClassAsWritten,
7374 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00007375
7376 // Parameters can not be abstract class types.
7377 // For record types, this is done by the AbstractClassUsageDiagnoser once
7378 // the class has been completely parsed.
7379 if (!CurContext->isRecord() &&
7380 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7381 AbstractParamType))
7382 New->setInvalidDecl();
7383
7384 // Parameter declarators cannot be interface types. All ObjC objects are
7385 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00007386 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00007387 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00007388 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00007389 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00007390 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00007391 T = Context.getObjCObjectPointerType(T);
7392 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00007393 }
7394
7395 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7396 // duration shall not be qualified by an address-space qualifier."
7397 // Since all parameters have automatic store duration, they can not have
7398 // an address space.
7399 if (T.getAddressSpace() != 0) {
7400 Diag(NameLoc, diag::err_arg_with_address_space);
7401 New->setInvalidDecl();
7402 }
7403
7404 return New;
7405}
7406
Douglas Gregor170512f2009-04-01 23:51:29 +00007407void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7408 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007409 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007410
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007411 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7412 // for a K&R function.
7413 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00007414 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7415 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007416 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007417 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00007418 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00007419 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00007420 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007421 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00007422 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00007423 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00007424
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007425 // Implicitly declare the argument as type 'int' for lack of a better
7426 // type.
John McCall084e83d2011-03-24 11:26:52 +00007427 AttributeFactory attrs;
7428 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007429 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00007430 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00007431 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00007432 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007433 Declarator ParamD(DS, Declarator::KNRTypeListContext);
7434 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00007435 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00007436 }
7437 }
Mike Stump11289f42009-09-09 15:08:12 +00007438 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00007439}
7440
Richard Smith79a52e52012-04-17 22:30:01 +00007441Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00007442 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007443 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00007444 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00007445
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007446 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00007447 Decl *DP = HandleDeclarator(ParentScope, D,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007448 MultiTemplateParamsArg(*this));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00007449 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007450}
7451
Anders Carlsson31c7e882009-12-09 03:30:09 +00007452static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7453 // Don't warn about invalid declarations.
7454 if (FD->isInvalidDecl())
7455 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007456
Anders Carlsson31c7e882009-12-09 03:30:09 +00007457 // Or declarations that aren't global.
7458 if (!FD->isGlobal())
7459 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007460
Anders Carlsson31c7e882009-12-09 03:30:09 +00007461 // Don't warn about C++ member functions.
7462 if (isa<CXXMethodDecl>(FD))
7463 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007464
Anders Carlsson31c7e882009-12-09 03:30:09 +00007465 // Don't warn about 'main'.
7466 if (FD->isMain())
7467 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007468
Anders Carlsson31c7e882009-12-09 03:30:09 +00007469 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00007470 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00007471 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00007472
7473 // Don't warn about function templates.
7474 if (FD->getDescribedFunctionTemplate())
7475 return false;
7476
7477 // Don't warn about function template specializations.
7478 if (FD->isFunctionTemplateSpecialization())
7479 return false;
7480
Anders Carlsson31c7e882009-12-09 03:30:09 +00007481 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00007482 for (const FunctionDecl *Prev = FD->getPreviousDecl();
7483 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00007484 // Ignore any declarations that occur in function or method
7485 // scope, because they aren't visible from the header.
7486 if (Prev->getDeclContext()->isFunctionOrMethod())
7487 continue;
7488
7489 MissingPrototype = !Prev->getType()->isFunctionProtoType();
7490 break;
7491 }
7492
7493 return MissingPrototype;
7494}
7495
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007496void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7497 // Don't complain if we're in GNU89 mode and the previous definition
7498 // was an extern inline function.
7499 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007500 if (FD->isDefined(Definition) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007501 !canRedefineFunction(Definition, getLangOpts())) {
7502 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007503 Definition->getStorageClass() == SC_Extern)
7504 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007505 << FD->getDeclName() << getLangOpts().CPlusPlus;
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007506 else
7507 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7508 Diag(Definition->getLocation(), diag::note_previous_definition);
7509 }
7510}
7511
John McCall48871652010-08-21 09:40:31 +00007512Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00007513 // Clear the last template instantiation error context.
7514 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7515
Douglas Gregor17a7c122009-06-24 00:54:41 +00007516 if (!D)
7517 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007518 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00007519
John McCall48871652010-08-21 09:40:31 +00007520 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007521 FD = FunTmpl->getTemplatedDecl();
7522 else
John McCall48871652010-08-21 09:40:31 +00007523 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007524
Douglas Gregor9a28e842010-03-01 23:15:13 +00007525 // Enter a new function scope
7526 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00007527
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007528 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00007529 if (!FD->isLateTemplateParsed())
7530 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00007531
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007532 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00007533 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00007534 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007535 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00007536 FD->setInvalidDecl();
7537 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00007538 }
7539
Eli Friedman9ad72442009-03-04 07:30:59 +00007540 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00007541 // (C99 6.9.1p3, C++ [dcl.fct]p6).
7542 QualType ResultType = FD->getResultType();
7543 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00007544 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00007545 RequireCompleteType(FD->getLocation(), ResultType,
7546 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00007547 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00007548
Douglas Gregorf1b876d2009-03-31 16:35:03 +00007549 // GNU warning -Wmissing-prototypes:
7550 // Warn if a global function is defined without a previous
7551 // prototype declaration. This warning is issued even if the
7552 // definition itself provides a prototype. The aim is to detect
7553 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00007554 if (ShouldWarnAboutMissingPrototype(FD))
7555 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00007556
Douglas Gregor67da0d92009-05-15 17:59:04 +00007557 if (FnBodyScope)
7558 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007559
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007560 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00007561 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7562 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007563
7564 // Introduce our parameters into the function scope
7565 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7566 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00007567 Param->setOwningFunction(FD);
7568
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007569 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00007570 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00007571 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00007572
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00007573 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00007574 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00007575 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00007576
James Molloy6f8780b2012-02-29 10:24:19 +00007577 // If we had any tags defined in the function prototype,
7578 // introduce them into the function scope.
7579 if (FnBodyScope) {
7580 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7581 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7582 NamedDecl *D = *I;
7583
7584 // Some of these decls (like enums) may have been pinned to the translation unit
7585 // for lack of a real context earlier. If so, remove from the translation unit
7586 // and reattach to the current context.
7587 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7588 // Is the decl actually in the context?
7589 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7590 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7591 if (*DI == D) {
7592 Context.getTranslationUnitDecl()->removeDecl(D);
7593 break;
7594 }
7595 }
7596 // Either way, reassign the lexical decl context to our FunctionDecl.
7597 D->setLexicalDeclContext(CurContext);
7598 }
7599
7600 // If the decl has a non-null name, make accessible in the current scope.
7601 if (!D->getName().empty())
7602 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7603
7604 // Similarly, dive into enums and fish their constants out, making them
7605 // accessible in this scope.
7606 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7607 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7608 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00007609 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00007610 }
7611 }
7612 }
7613
Richard Smith79a52e52012-04-17 22:30:01 +00007614 // Ensure that the function's exception specification is instantiated.
7615 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7616 ResolveExceptionSpec(D->getLocation(), FPT);
7617
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007618 // Checking attributes of current function definition
7619 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007620 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7621 if (DA && (!FD->getAttr<DLLExportAttr>())) {
7622 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00007623 // Microsoft accepts dllimport for functions defined within class scope.
7624 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00007625 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007626 Diag(FD->getLocation(),
7627 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7628 << "dllimport";
7629 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00007630 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00007631 }
7632
7633 // Visual C++ appears to not think this is an issue, so only issue
7634 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00007635 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007636 // If a symbol previously declared dllimport is later defined, the
7637 // attribute is ignored in subsequent references, and a warning is
7638 // emitted.
7639 Diag(FD->getLocation(),
7640 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00007641 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00007642 }
7643 }
John McCall48871652010-08-21 09:40:31 +00007644 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00007645}
7646
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007647/// \brief Given the set of return statements within a function body,
7648/// compute the variables that are subject to the named return value
7649/// optimization.
7650///
7651/// Each of the variables that is subject to the named return value
7652/// optimization will be marked as NRVO variables in the AST, and any
7653/// return statement that has a marked NRVO variable as its NRVO candidate can
7654/// use the named return value optimization.
7655///
7656/// This function applies a very simplistic algorithm for NRVO: if every return
7657/// statement in the function has the same NRVO candidate, that candidate is
7658/// the NRVO variable.
7659///
7660/// FIXME: Employ a smarter algorithm that accounts for multiple return
7661/// statements and the lifetimes of the NRVO candidates. We should be able to
7662/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00007663void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00007664 ReturnStmt **Returns = Scope->Returns.data();
7665
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007666 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00007667 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007668 if (!Returns[I]->getNRVOCandidate())
7669 return;
7670
7671 if (!NRVOCandidate)
7672 NRVOCandidate = Returns[I]->getNRVOCandidate();
7673 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7674 return;
7675 }
7676
7677 if (NRVOCandidate)
7678 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7679}
7680
John McCallfaf5fb42010-08-26 23:41:50 +00007681Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00007682 return ActOnFinishFunctionBody(D, move(BodyArg), false);
7683}
7684
John McCallb268a282010-08-23 23:25:46 +00007685Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7686 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007687 FunctionDecl *FD = 0;
7688 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7689 if (FunTmpl)
7690 FD = FunTmpl->getTemplatedDecl();
7691 else
7692 FD = dyn_cast_or_null<FunctionDecl>(dcl);
7693
Ted Kremenek0b405322010-03-23 00:13:23 +00007694 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00007695 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00007696
Douglas Gregorc45a40a2009-08-22 00:34:47 +00007697 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00007698 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00007699
7700 // If the function implicitly returns zero (like 'main') or is naked,
7701 // don't complain about missing return statements.
7702 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00007703 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00007704
Francois Pichet3abc9b82011-05-11 02:14:46 +00007705 // MSVC permits the use of pure specifier (=0) on function definition,
7706 // defined at class scope, warn about this non standard construct.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007707 if (getLangOpts().MicrosoftExt && FD->isPure())
Francois Pichet3abc9b82011-05-11 02:14:46 +00007708 Diag(FD->getLocation(), diag::warn_pure_function_definition);
7709
Douglas Gregor88d292c2010-05-13 16:44:06 +00007710 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007711 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007712 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7713 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007714
7715 // If this is a constructor, we need a vtable.
7716 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7717 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00007718
Jordan Rosed39e5f12012-07-02 21:19:23 +00007719 // Try to apply the named return value optimization. We have to check
7720 // if we can do this here because lambdas keep return statements around
7721 // to deduce an implicit return type.
7722 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
7723 !FD->isDependentContext())
7724 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00007725 }
7726
Douglas Gregor21f46922012-02-08 20:17:14 +00007727 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7728 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00007729 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00007730 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00007731 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007732 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007733 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007734 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7735 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00007736
7737 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00007738 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00007739 }
Nico Weber715abaf2011-08-22 17:25:57 +00007740 if (ObjCShouldCallSuperDealloc) {
7741 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7742 ObjCShouldCallSuperDealloc = false;
7743 }
Nico Weber1fb82662011-08-28 22:35:17 +00007744 if (ObjCShouldCallSuperFinalize) {
7745 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7746 ObjCShouldCallSuperFinalize = false;
7747 }
Ted Kremenek5a201952009-02-07 01:47:29 +00007748 } else {
John McCall48871652010-08-21 09:40:31 +00007749 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00007750 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00007751
Nico Weber715abaf2011-08-22 17:25:57 +00007752 assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7753 "ObjC methods, which should have been handled in the block above.");
Nico Weber1fb82662011-08-28 22:35:17 +00007754 assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7755 "ObjC methods, which should have been handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00007756
Chris Lattnere2473062007-05-28 06:28:18 +00007757 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00007758 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00007759 // C++ constructors that have function-try-blocks can't have return
7760 // statements in the handlers of that block. (C++ [except.handle]p14)
7761 // Verify this.
7762 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7763 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7764
Richard Smithdef8bdb2011-08-12 18:44:32 +00007765 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00007766 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00007767 !dcl->isInvalidDecl() &&
John McCall31168b02011-06-15 23:02:42 +00007768 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00007769 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00007770
John McCalldeb646e2010-08-04 01:04:25 +00007771 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7772 if (!Destructor->getParent()->isDependentType())
7773 CheckDestructor(Destructor);
7774
John McCalla6309952010-03-16 21:39:52 +00007775 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7776 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00007777 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00007778
7779 // If any errors have occurred, clear out any temporaries that may have
7780 // been leftover. This ensures that these temporaries won't be picked up for
7781 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00007782 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00007783 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00007784 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00007785 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00007786 // Since the body is valid, issue any analysis-based warnings that are
7787 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00007788 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00007789 }
7790
Richard Smith3607ffe2012-02-13 03:54:03 +00007791 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7792 (!CheckConstexprFunctionDecl(FD) ||
7793 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00007794 FD->setInvalidDecl();
7795
John McCall28fc7092011-11-10 05:35:25 +00007796 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00007797 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00007798 assert(MaybeODRUseExprs.empty() &&
7799 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00007800 }
7801
John McCalle99d5f32010-03-25 22:08:03 +00007802 if (!IsInstantiation)
7803 PopDeclContext();
7804
Eli Friedman71c80552012-01-05 03:35:19 +00007805 PopFunctionScopeInfo(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00007806
Douglas Gregora7e3ea32009-11-15 07:07:58 +00007807 // If any errors have occurred, clear out any temporaries that may have
7808 // been leftover. This ensures that these temporaries won't be picked up for
7809 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00007810 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00007811 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00007812 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00007813
John McCall48871652010-08-21 09:40:31 +00007814 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00007815}
7816
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00007817
7818/// When we finish delayed parsing of an attribute, we must attach it to the
7819/// relevant Decl.
7820void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7821 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00007822 // Always attach attributes to the underlying decl.
7823 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7824 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00007825 ProcessDeclAttributeList(S, D, Attrs.getList());
7826
7827 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
7828 if (Method->isStatic())
7829 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00007830}
7831
7832
Chris Lattnerac18be92006-11-20 06:49:47 +00007833/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7834/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00007835NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00007836 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00007837 // Before we produce a declaration for an implicitly defined
7838 // function, see whether there was a locally-scoped declaration of
7839 // this name as a function or variable. If so, use that
7840 // (non-visible) declaration, and complain about it.
7841 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregordc5c9582011-07-28 14:20:37 +00007842 = findLocallyScopedExternalDecl(&II);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00007843 if (Pos != LocallyScopedExternalDecls.end()) {
7844 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7845 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7846 return Pos->second;
7847 }
7848
Chris Lattner00e26072008-05-05 21:18:06 +00007849 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00007850 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00007851 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00007852 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007853 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00007854 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00007855 else
Hans Wennborg70a13242011-12-08 15:56:07 +00007856 diag_id = diag::warn_implicit_function_decl;
7857 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00007858
Hans Wennborg70a13242011-12-08 15:56:07 +00007859 // Because typo correction is expensive, only do it if the implicit
7860 // function declaration is going to be treated as an error.
7861 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7862 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007863 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00007864 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00007865 LookupOrdinaryName, S, 0, Validator))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007866 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7867 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007868 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
Hans Wennborg70a13242011-12-08 15:56:07 +00007869
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007870 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7871 << FixItHint::CreateReplacement(Loc, CorrectedStr);
Hans Wennborg70a13242011-12-08 15:56:07 +00007872
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00007873 if (Func->getLocation().isValid()
7874 && !II.getName().startswith("__builtin_"))
7875 Diag(Func->getLocation(), diag::note_previous_decl)
7876 << CorrectedQuotedStr;
Hans Wennborg70a13242011-12-08 15:56:07 +00007877 }
Hans Wennborg2fb8b912011-12-06 09:46:12 +00007878 }
7879
Chris Lattnerac18be92006-11-20 06:49:47 +00007880 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00007881 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00007882 AttributeFactory attrFactory;
7883 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00007884 unsigned DiagID;
7885 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007886 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00007887 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00007888 Declarator D(DS, Declarator::BlockContext);
John McCall084e83d2011-03-24 11:26:52 +00007889 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00007890 0, 0, true, SourceLocation(),
Douglas Gregore248eea2011-10-19 06:04:55 +00007891 SourceLocation(), SourceLocation(),
Douglas Gregorad69e652011-07-13 21:47:47 +00007892 SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00007893 EST_None, SourceLocation(),
Richard Smith2331bbf2012-05-02 22:22:32 +00007894 0, 0, 0, 0, Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00007895 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00007896 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00007897 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00007898
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00007899 // Insert this function into translation-unit scope.
7900
7901 DeclContext *PrevDC = CurContext;
7902 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00007903
John McCall48871652010-08-21 09:40:31 +00007904 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00007905 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00007906
7907 CurContext = PrevDC;
7908
Douglas Gregore711f702009-02-14 18:57:46 +00007909 AddKnownFunctionAttributes(FD);
7910
Steve Naroff3913ea42008-04-04 14:32:09 +00007911 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00007912}
7913
Douglas Gregore711f702009-02-14 18:57:46 +00007914/// \brief Adds any function attributes that we know a priori based on
7915/// the declaration of this function.
7916///
7917/// These attributes can apply both to implicitly-declared builtins
7918/// (like __builtin___printf_chk) or to library-declared functions
7919/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00007920///
7921/// We need to check for duplicate attributes both here and where user-written
7922/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00007923void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7924 if (FD->isInvalidDecl())
7925 return;
7926
7927 // If this is a built-in function, map its builtin attributes to
7928 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00007929 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00007930 // Handle printf-formatting attributes.
7931 unsigned FormatIdx;
7932 bool HasVAListArg;
7933 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007934 if (!FD->getAttr<FormatAttr>()) {
7935 const char *fmt = "printf";
7936 unsigned int NumParams = FD->getNumParams();
7937 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7938 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7939 fmt = "NSString";
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007940 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007941 fmt, FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00007942 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007943 }
Douglas Gregore711f702009-02-14 18:57:46 +00007944 }
Ted Kremenek5932c352010-07-16 02:11:15 +00007945 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7946 HasVAListArg)) {
7947 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007948 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7949 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00007950 HasVAListArg ? 0 : FormatIdx+2));
7951 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00007952
7953 // Mark const if we don't care about errno and that is the only
7954 // thing preventing the function from being const. This allows
7955 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007956 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00007957 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007958 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007959 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00007960 }
Mike Stumpca6c8752009-07-27 19:14:18 +00007961
Rafael Espindola2d21ab02011-10-12 19:51:18 +00007962 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7963 !FD->getAttr<ReturnsTwiceAttr>())
7964 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00007965 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007966 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00007967 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007968 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00007969 }
7970
7971 IdentifierInfo *Name = FD->getIdentifier();
7972 if (!Name)
7973 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007974 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00007975 FD->getDeclContext()->isTranslationUnit()) ||
7976 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00007977 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00007978 LinkageSpecDecl::lang_c)) {
7979 // Okay: this could be a libc/libm/Objective-C function we know
7980 // about.
7981 } else
7982 return;
7983
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +00007984 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00007985 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00007986 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007987 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007988 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7989 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00007990 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00007991 }
Douglas Gregore711f702009-02-14 18:57:46 +00007992}
Chris Lattner302b4be2006-11-19 02:31:38 +00007993
John McCall703a3f82009-10-24 08:00:42 +00007994TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00007995 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00007996 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00007997 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00007998
John McCallbcd03502009-12-07 02:54:59 +00007999 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00008000 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00008001 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00008002 }
8003
Chris Lattner18b19622007-01-22 07:39:13 +00008004 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00008005 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008006 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00008007 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00008008 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00008009 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00008010
John McCall04fcd0d2011-02-01 08:20:08 +00008011 // Bail out immediately if we have an invalid declaration.
8012 if (D.isInvalidType()) {
8013 NewTD->setInvalidDecl();
8014 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00008015 }
8016
Douglas Gregor41866812011-09-12 18:37:38 +00008017 if (D.getDeclSpec().isModulePrivateSpecified()) {
8018 if (CurContext->isFunctionOrMethod())
8019 Diag(NewTD->getLocation(), diag::err_module_private_local)
8020 << 2 << NewTD->getDeclName()
8021 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8022 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8023 else
8024 NewTD->setModulePrivate();
8025 }
Douglas Gregor26701a42011-09-09 02:06:17 +00008026
John McCall04fcd0d2011-02-01 08:20:08 +00008027 // C++ [dcl.typedef]p8:
8028 // If the typedef declaration defines an unnamed class (or
8029 // enum), the first typedef-name declared by the declaration
8030 // to be that class type (or enum type) is used to denote the
8031 // class type (or enum type) for linkage purposes only.
8032 // We need to check whether the type was declared in the declaration.
8033 switch (D.getDeclSpec().getTypeSpecType()) {
8034 case TST_enum:
8035 case TST_struct:
8036 case TST_union:
8037 case TST_class: {
8038 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
8039
8040 // Do nothing if the tag is not anonymous or already has an
8041 // associated typedef (from an earlier typedef in this decl group).
8042 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00008043 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00008044
8045 // A well-formed anonymous tag must always be a TUK_Definition.
8046 assert(tagFromDeclSpec->isThisDeclarationADefinition());
8047
8048 // The type must match the tag exactly; no qualifiers allowed.
8049 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
8050 break;
8051
8052 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00008053 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00008054 break;
8055 }
8056
8057 default:
8058 break;
8059 }
8060
Steve Narofff93b6722007-08-28 20:14:24 +00008061 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00008062}
8063
Douglas Gregord9034f02009-05-14 16:41:31 +00008064
Richard Smith4b38ded2012-03-14 23:13:10 +00008065/// \brief Check that this is a valid underlying type for an enum declaration.
8066bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
8067 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
8068 QualType T = TI->getType();
8069
8070 if (T->isDependentType() || T->isIntegralType(Context))
8071 return false;
8072
8073 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
8074 return true;
8075}
8076
8077/// Check whether this is a valid redeclaration of a previous enumeration.
8078/// \return true if the redeclaration was invalid.
8079bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
8080 QualType EnumUnderlyingTy,
8081 const EnumDecl *Prev) {
8082 bool IsFixed = !EnumUnderlyingTy.isNull();
8083
8084 if (IsScoped != Prev->isScoped()) {
8085 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
8086 << Prev->isScoped();
8087 Diag(Prev->getLocation(), diag::note_previous_use);
8088 return true;
8089 }
8090
8091 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +00008092 if (!EnumUnderlyingTy->isDependentType() &&
8093 !Prev->getIntegerType()->isDependentType() &&
8094 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +00008095 Prev->getIntegerType())) {
8096 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
8097 << EnumUnderlyingTy << Prev->getIntegerType();
8098 Diag(Prev->getLocation(), diag::note_previous_use);
8099 return true;
8100 }
8101 } else if (IsFixed != Prev->isFixed()) {
8102 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
8103 << Prev->isFixed();
8104 Diag(Prev->getLocation(), diag::note_previous_use);
8105 return true;
8106 }
8107
8108 return false;
8109}
8110
Douglas Gregord9034f02009-05-14 16:41:31 +00008111/// \brief Determine whether a tag with a given kind is acceptable
8112/// as a redeclaration of the given tag declaration.
8113///
8114/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00008115bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00008116 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00008117 SourceLocation NewTagLoc,
8118 const IdentifierInfo &Name) {
8119 // C++ [dcl.type.elab]p3:
8120 // The class-key or enum keyword present in the
8121 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00008122 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00008123 // refers. This rule also applies to the form of
8124 // elaborated-type-specifier that declares a class-name or
8125 // friend class since it can be construed as referring to the
8126 // definition of the class. Thus, in any
8127 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00008128 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00008129 // used to refer to a union (clause 9), and either the class or
8130 // struct class-key shall be used to refer to a class (clause 9)
8131 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008132 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieucaa33d32011-06-10 03:11:26 +00008133 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
8134 if (OldTag == NewTag)
8135 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008136
Abramo Bagnara6150c882010-05-11 21:36:43 +00008137 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
8138 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00008139 // Warn about the struct/class tag mismatch.
8140 bool isTemplate = false;
8141 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
8142 isTemplate = Record->getDescribedClassTemplate();
8143
Richard Trieucaa33d32011-06-10 03:11:26 +00008144 if (!ActiveTemplateInstantiations.empty()) {
8145 // In a template instantiation, do not offer fix-its for tag mismatches
8146 // since they usually mess up the template instead of fixing the problem.
8147 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8148 << (NewTag == TTK_Class) << isTemplate << &Name;
8149 return true;
8150 }
8151
8152 if (isDefinition) {
8153 // On definitions, check previous tags and issue a fix-it for each
8154 // one that doesn't match the current tag.
8155 if (Previous->getDefinition()) {
8156 // Don't suggest fix-its for redefinitions.
8157 return true;
8158 }
8159
8160 bool previousMismatch = false;
8161 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
8162 E(Previous->redecls_end()); I != E; ++I) {
8163 if (I->getTagKind() != NewTag) {
8164 if (!previousMismatch) {
8165 previousMismatch = true;
8166 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
8167 << (NewTag == TTK_Class) << isTemplate << &Name;
8168 }
8169 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
8170 << (NewTag == TTK_Class)
8171 << FixItHint::CreateReplacement(I->getInnerLocStart(),
8172 NewTag == TTK_Class?
8173 "class" : "struct");
8174 }
8175 }
8176 return true;
8177 }
8178
8179 // Check for a previous definition. If current tag and definition
8180 // are same type, do nothing. If no definition, but disagree with
8181 // with previous tag type, give a warning, but no fix-it.
8182 const TagDecl *Redecl = Previous->getDefinition() ?
8183 Previous->getDefinition() : Previous;
8184 if (Redecl->getTagKind() == NewTag) {
8185 return true;
8186 }
8187
Douglas Gregord9034f02009-05-14 16:41:31 +00008188 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008189 << (NewTag == TTK_Class)
Richard Trieucaa33d32011-06-10 03:11:26 +00008190 << isTemplate << &Name;
8191 Diag(Redecl->getLocation(), diag::note_previous_use);
8192
8193 // If there is a previous defintion, suggest a fix-it.
8194 if (Previous->getDefinition()) {
8195 Diag(NewTagLoc, diag::note_struct_class_suggestion)
8196 << (Redecl->getTagKind() == TTK_Class)
8197 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
8198 Redecl->getTagKind() == TTK_Class? "class" : "struct");
8199 }
8200
Douglas Gregord9034f02009-05-14 16:41:31 +00008201 return true;
8202 }
8203 return false;
8204}
8205
Steve Naroff30d242c2007-09-15 18:49:24 +00008206/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00008207/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00008208/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00008209/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00008210Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00008211 SourceLocation KWLoc, CXXScopeSpec &SS,
8212 IdentifierInfo *Name, SourceLocation NameLoc,
8213 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00008214 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +00008215 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00008216 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +00008217 SourceLocation ScopedEnumKWLoc,
8218 bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00008219 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008220 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008221 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +00008222 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00008223 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00008224 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008225
Douglas Gregord6ab8742009-05-28 23:31:59 +00008226 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00008227 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +00008228 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +00008229
Douglas Gregor5c0405d2009-10-07 22:35:40 +00008230 // FIXME: Check explicit specializations more carefully.
8231 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008232 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00008233
8234 // We only need to do this matching if we have template parameters
8235 // or a scope specifier, which also conveniently avoids this work
8236 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00008237 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00008238 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00008239 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008240 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00008241 TemplateParameterLists.get(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00008242 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00008243 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008244 isExplicitSpecialization,
8245 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00008246 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00008247 // This is a declaration or definition of a class template (which may
8248 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00008249
Douglas Gregor5f0e2522010-07-14 23:14:12 +00008250 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00008251 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008252
Douglas Gregore93e46c2009-07-22 23:48:44 +00008253 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00008254 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00008255 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008256 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00008257 ModulePrivateLoc,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008258 TemplateParameterLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008259 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00008260 return Result.get();
8261 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008262 // The "template<>" header is extraneous.
8263 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008264 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008265 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00008266 }
Mike Stump11289f42009-09-09 15:08:12 +00008267 }
8268 }
8269
Douglas Gregor0bf31402010-10-08 23:50:27 +00008270 // Figure out the underlying type if this a enum declaration. We need to do
8271 // this early, because it's needed to detect if this is an incompatible
8272 // redeclaration.
8273 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8274
8275 if (Kind == TTK_Enum) {
8276 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8277 // No underlying type explicitly specified, or we failed to parse the
8278 // type, default to int.
8279 EnumUnderlying = Context.IntTy.getTypePtr();
8280 else if (UnderlyingType.get()) {
8281 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8282 // integral type; any cv-qualification is ignored.
8283 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +00008284 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008285 EnumUnderlying = TI;
8286
Richard Smith4b38ded2012-03-14 23:13:10 +00008287 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +00008288 // Recover by falling back to int.
8289 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008290
Richard Smith4b38ded2012-03-14 23:13:10 +00008291 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008292 UPPC_FixedUnderlyingType))
8293 EnumUnderlying = Context.IntTy.getTypePtr();
8294
David Blaikiebbafb8a2012-03-11 07:00:24 +00008295 } else if (getLangOpts().MicrosoftMode)
Francois Picheta3108062010-10-18 15:01:13 +00008296 // Microsoft enums are always of int type.
8297 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008298 }
8299
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008300 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008301 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00008302 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00008303
Chandler Carrutha419dbb2010-03-01 21:17:36 +00008304 RedeclarationKind Redecl = ForRedeclaration;
8305 if (TUK == TUK_Friend || TUK == TUK_Reference)
8306 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00008307
8308 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00008309
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008310 if (Name && SS.isNotEmpty()) {
8311 // We have a nested-name tag ('struct foo::bar').
8312
8313 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008314 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008315 Name = 0;
8316 goto CreateNewDecl;
8317 }
8318
John McCall7f41d982009-09-11 04:59:25 +00008319 // If this is a friend or a reference to a class in a dependent
8320 // context, don't try to make a decl for it.
8321 if (TUK == TUK_Friend || TUK == TUK_Reference) {
8322 DC = computeDeclContext(SS, false);
8323 if (!DC) {
8324 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00008325 return 0;
John McCall7f41d982009-09-11 04:59:25 +00008326 }
John McCall0b66eb32010-05-01 00:40:08 +00008327 } else {
8328 DC = computeDeclContext(SS, true);
8329 if (!DC) {
8330 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8331 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008332 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00008333 }
John McCall7f41d982009-09-11 04:59:25 +00008334 }
8335
John McCall0b66eb32010-05-01 00:40:08 +00008336 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00008337 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00008338
Douglas Gregor8761da52009-02-03 00:34:39 +00008339 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00008340 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00008341 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00008342
John McCall1f82f242009-11-18 22:49:29 +00008343 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008344 return 0;
John McCall6538c932009-10-10 05:48:19 +00008345
John McCall1f82f242009-11-18 22:49:29 +00008346 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00008347 // Name lookup did not find anything. However, if the
8348 // nested-name-specifier refers to the current instantiation,
8349 // and that current instantiation has any dependent base
8350 // classes, we might find something at instantiation time: treat
8351 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00008352 // But this only makes any sense for reference-like lookups.
8353 if (Previous.wasNotFoundInCurrentInstantiation() &&
8354 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00008355 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00008356 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00008357 }
8358
8359 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00008360 Diag(NameLoc, diag::err_not_tag_in_scope)
8361 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008362 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008363 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008364 goto CreateNewDecl;
8365 }
Chris Lattnerd9773512009-01-21 02:38:50 +00008366 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008367 // If this is a named struct, check to see if there was a previous forward
8368 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00008369 // FIXME: We're looking into outer scopes here, even when we
8370 // shouldn't be. Doing so can result in ambiguities that we
8371 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00008372 LookupName(Previous, S);
8373
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00008374 if (Previous.isAmbiguous() &&
8375 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00008376 LookupResult::Filter F = Previous.makeFilter();
8377 while (F.hasNext()) {
8378 NamedDecl *ND = F.next();
8379 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8380 F.erase();
8381 }
8382 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00008383 }
8384
John McCall1f82f242009-11-18 22:49:29 +00008385 // Note: there used to be some attempt at recovery here.
8386 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008387 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008388
David Blaikiebbafb8a2012-03-11 07:00:24 +00008389 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008390 // FIXME: This makes sure that we ignore the contexts associated
8391 // with C structs, unions, and enums when looking for a matching
8392 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00008393 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008394 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8395 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008396 }
Douglas Gregor009f6992010-09-16 23:58:57 +00008397 } else if (S->isFunctionPrototypeScope()) {
8398 // If this is an enum declaration in function prototype scope, set its
8399 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +00008400 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +00008401 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00008402 }
8403
John McCall1f82f242009-11-18 22:49:29 +00008404 if (Previous.isSingleResult() &&
8405 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00008406 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00008407 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00008408 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00008409 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00008410 }
8411
David Blaikiebbafb8a2012-03-11 07:00:24 +00008412 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008413 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008414 // This is a declaration of or a reference to "std::bad_alloc".
8415 isStdBadAlloc = true;
8416
John McCall1f82f242009-11-18 22:49:29 +00008417 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008418 // std::bad_alloc has been implicitly declared (but made invisible to
8419 // name lookup). Fill in this implicit declaration as the previous
8420 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008421 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00008422 }
8423 }
John McCall1f82f242009-11-18 22:49:29 +00008424
John McCalle9eaf8e2010-03-25 21:28:06 +00008425 // If we didn't find a previous declaration, and this is a reference
8426 // (or friend reference), move to the correct scope. In C++, we
8427 // also need to do a redeclaration lookup there, just in case
8428 // there's a shadow friend decl.
8429 if (Name && Previous.empty() &&
8430 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8431 if (Invalid) goto CreateNewDecl;
8432 assert(SS.isEmpty());
8433
8434 if (TUK == TUK_Reference) {
8435 // C++ [basic.scope.pdecl]p5:
8436 // -- for an elaborated-type-specifier of the form
8437 //
8438 // class-key identifier
8439 //
8440 // if the elaborated-type-specifier is used in the
8441 // decl-specifier-seq or parameter-declaration-clause of a
8442 // function defined in namespace scope, the identifier is
8443 // declared as a class-name in the namespace that contains
8444 // the declaration; otherwise, except as a friend
8445 // declaration, the identifier is declared in the smallest
8446 // non-class, non-function-prototype scope that contains the
8447 // declaration.
8448 //
8449 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8450 // C structs and unions.
8451 //
8452 // It is an error in C++ to declare (rather than define) an enum
8453 // type, including via an elaborated type specifier. We'll
8454 // diagnose that later; for now, declare the enum in the same
8455 // scope as we would have picked for any other tag type.
8456 //
8457 // GNU C also supports this behavior as part of its incomplete
8458 // enum types extension, while GNU C++ does not.
8459 //
8460 // Find the context where we'll be declaring the tag.
8461 // FIXME: We would like to maintain the current DeclContext as the
8462 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +00008463 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +00008464 SearchDC = SearchDC->getParent();
8465
8466 // Find the scope where we'll be declaring the tag.
8467 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008468 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +00008469 S->isFunctionPrototypeScope()) ||
8470 ((S->getFlags() & Scope::DeclScope) == 0) ||
8471 (S->getEntity() &&
8472 ((DeclContext *)S->getEntity())->isTransparentContext()))
8473 S = S->getParent();
8474 } else {
8475 assert(TUK == TUK_Friend);
8476 // C++ [namespace.memdef]p3:
8477 // If a friend declaration in a non-local class first declares a
8478 // class or function, the friend class or function is a member of
8479 // the innermost enclosing namespace.
8480 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00008481 }
8482
John McCalle87beb22010-04-23 18:46:30 +00008483 // In C++, we need to do a redeclaration lookup to properly
8484 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008485 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +00008486 Previous.setRedeclarationKind(ForRedeclaration);
8487 LookupQualifiedName(Previous, SearchDC);
8488 }
8489 }
8490
John McCall1f82f242009-11-18 22:49:29 +00008491 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00008492 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00008493
8494 // It's okay to have a tag decl in the same scope as a typedef
8495 // which hides a tag decl in the same scope. Finding this
8496 // insanity with a redeclaration lookup can only actually happen
8497 // in C++.
8498 //
8499 // This is also okay for elaborated-type-specifiers, which is
8500 // technically forbidden by the current standard but which is
8501 // okay according to the likely resolution of an open issue;
8502 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +00008503 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00008504 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00008505 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8506 TagDecl *Tag = TT->getDecl();
8507 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008508 Tag->getDeclContext()->getRedeclContext()
8509 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00008510 PrevDecl = Tag;
8511 Previous.clear();
8512 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00008513 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00008514 }
8515 }
8516 }
8517 }
8518
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008519 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00008520 // If this is a use of a previous tag, or if the tag is already declared
8521 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008522 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00008523 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00008524 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00008525 // Make sure that this wasn't declared as an enum and now used as a
8526 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00008527 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8528 TUK == TUK_Definition, KWLoc,
8529 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00008530 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00008531 = (PrevTagDecl->getTagKind() != TTK_Enum &&
8532 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00008533 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00008534 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00008535 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00008536 << FixItHint::CreateReplacement(SourceRange(KWLoc),
8537 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00008538 else
8539 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00008540 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00008541
Mike Stump11289f42009-09-09 15:08:12 +00008542 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00008543 Kind = PrevTagDecl->getTagKind();
8544 else {
8545 // Recover by making this an anonymous redefinition.
8546 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008547 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00008548 Invalid = true;
8549 }
8550 }
8551
Douglas Gregor0bf31402010-10-08 23:50:27 +00008552 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8553 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8554
Richard Smith0f8ee222012-01-10 01:33:14 +00008555 // If this is an elaborated-type-specifier for a scoped enumeration,
8556 // the 'class' keyword is not necessary and not permitted.
8557 if (TUK == TUK_Reference || TUK == TUK_Friend) {
8558 if (ScopedEnum)
8559 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8560 << PrevEnum->isScoped()
8561 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8562 return PrevTagDecl;
8563 }
8564
Richard Smith4b38ded2012-03-14 23:13:10 +00008565 QualType EnumUnderlyingTy;
8566 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8567 EnumUnderlyingTy = TI->getType();
8568 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8569 EnumUnderlyingTy = QualType(T, 0);
8570
Douglas Gregor0bf31402010-10-08 23:50:27 +00008571 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +00008572 // returning the previous declaration, unless this is a definition,
8573 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +00008574 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8575 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +00008576 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +00008577 }
8578
Douglas Gregor170512f2009-04-01 23:51:29 +00008579 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008580 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00008581
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008582 // FIXME: In the future, return a variant or some other clue
8583 // for the consumer of this Decl to know it doesn't own it.
8584 // For our current ASTs this shouldn't be a problem, but will
8585 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00008586 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008587 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00008588 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008589
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008590 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00008591 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00008592 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008593 // If we're defining a specialization and the previous definition
8594 // is from an implicit instantiation, don't emit an error
8595 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +00008596 bool IsExplicitSpecializationAfterInstantiation = false;
8597 if (isExplicitSpecialization) {
8598 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8599 IsExplicitSpecializationAfterInstantiation =
8600 RD->getTemplateSpecializationKind() !=
8601 TSK_ExplicitSpecialization;
8602 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8603 IsExplicitSpecializationAfterInstantiation =
8604 ED->getTemplateSpecializationKind() !=
8605 TSK_ExplicitSpecialization;
8606 }
8607
8608 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +00008609 // A redeclaration in function prototype scope in C isn't
8610 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008611 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +00008612 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8613 else
8614 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +00008615 Diag(Def->getLocation(), diag::note_previous_definition);
8616 // If this is a redefinition, recover by making this
8617 // struct be anonymous, which will make any later
8618 // references get the previous definition.
8619 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008620 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00008621 Invalid = true;
8622 }
Douglas Gregordee1be82009-01-17 00:42:38 +00008623 } else {
8624 // If the type is currently being defined, complain
8625 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00008626 const TagType *Tag
8627 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00008628 if (Tag->isBeingDefined()) {
8629 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00008630 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00008631 diag::note_previous_definition);
8632 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00008633 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00008634 Invalid = true;
8635 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008636 }
Douglas Gregordee1be82009-01-17 00:42:38 +00008637
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008638 // Okay, this is definition of a previously declared or referenced
8639 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00008640 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008641 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008642 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00008643 // have a definition. Just create a new decl.
8644
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008645 } else {
8646 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00008647 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008648 // new decl/type. We set PrevDecl to NULL so that the entities
8649 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00008650 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00008651 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008652 // If we get here, we're going to create a new Decl. If PrevDecl
8653 // is non-NULL, it's a definition of the tag declared by
8654 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00008655
8656
8657 // Otherwise, PrevDecl is not a tag, but was found with tag
8658 // lookup. This is only actually possible in C++, where a few
8659 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008660 } else {
John McCalle87beb22010-04-23 18:46:30 +00008661 // Use a better diagnostic if an elaborated-type-specifier
8662 // found the wrong kind of type on the first
8663 // (non-redeclaration) lookup.
8664 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8665 !Previous.isForRedeclaration()) {
8666 unsigned Kind = 0;
8667 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00008668 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8669 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00008670 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8671 Diag(PrevDecl->getLocation(), diag::note_declared_at);
8672 Invalid = true;
8673
8674 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00008675 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8676 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00008677 // do nothing
8678
8679 // Diagnose implicit declarations introduced by elaborated types.
8680 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8681 unsigned Kind = 0;
8682 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00008683 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8684 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00008685 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8686 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8687 Invalid = true;
8688
8689 // Otherwise it's a declaration. Call out a particularly common
8690 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00008691 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8692 unsigned Kind = 0;
8693 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00008694 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00008695 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00008696 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8697 Invalid = true;
8698
8699 // Otherwise, diagnose.
8700 } else {
8701 // The tag name clashes with something else in the target scope,
8702 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008703 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00008704 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00008705 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00008706 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00008707 }
John McCalle87beb22010-04-23 18:46:30 +00008708
8709 // The existing declaration isn't relevant to us; we're in a
8710 // new scope, so clear out the previous declaration.
8711 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00008712 }
Chris Lattner18b19622007-01-22 07:39:13 +00008713 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00008714
Chris Lattner438e5012008-12-17 07:13:27 +00008715CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00008716
John McCall1f82f242009-11-18 22:49:29 +00008717 TagDecl *PrevDecl = 0;
8718 if (Previous.isSingleResult())
8719 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8720
Chris Lattnerbf0b7982007-01-23 04:27:41 +00008721 // If there is an identifier, use the location of the identifier as the
8722 // location of the decl, otherwise use the location of the struct/union
8723 // keyword.
8724 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00008725
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008726 // Otherwise, create a new declaration. If there is a previous
8727 // declaration of the same entity, the two will be linked via
8728 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00008729 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00008730
Douglas Gregor0bf31402010-10-08 23:50:27 +00008731 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00008732 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00008733 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8734 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008735 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00008736 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00008737 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00008738 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00008739 if (TUK != TUK_Definition && !Invalid) {
8740 TagDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008741 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00008742 // C++0x: 7.2p2: opaque-enum-declaration.
8743 // Conflicts are diagnosed above. Do nothing.
8744 }
8745 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00008746 Diag(Loc, diag::ext_forward_ref_enum_def)
8747 << New;
8748 Diag(Def->getLocation(), diag::note_previous_definition);
8749 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00008750 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008751 if (getLangOpts().MicrosoftMode)
Francois Pichet488b4a72010-09-12 05:06:55 +00008752 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008753 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +00008754 DiagID = diag::err_forward_ref_enum;
8755 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008756
8757 // If this is a forward-declared reference to an enumeration, make a
8758 // note of it; we won't actually be introducing the declaration into
8759 // the declaration context.
8760 if (TUK == TUK_Reference)
8761 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00008762 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00008763 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00008764
8765 if (EnumUnderlying) {
8766 EnumDecl *ED = cast<EnumDecl>(New);
8767 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8768 ED->setIntegerTypeSourceInfo(TI);
8769 else
8770 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8771 ED->setPromotionType(ED->getIntegerType());
8772 }
8773
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00008774 } else {
8775 // struct/union/class
8776
Chris Lattner776fac82007-06-09 00:53:06 +00008777 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8778 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008779 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00008780 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008781 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008782 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008783
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008784 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00008785 StdBadAlloc = cast<CXXRecordDecl>(New);
8786 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008787 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008788 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00008789 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008790
John McCall3e11ebe2010-03-15 10:12:16 +00008791 // Maybe add qualifier info.
8792 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00008793 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008794 // If this is either a declaration or a definition, check the
8795 // nested-name-specifier against the current context. We don't do this
8796 // for explicit specializations, because they have similar checking
8797 // (with more specific diagnostics) in the call to
8798 // CheckMemberSpecialization, below.
8799 if (!isExplicitSpecialization &&
8800 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
8801 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
8802 Invalid = true;
8803
Douglas Gregor14454802011-02-25 02:25:35 +00008804 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00008805 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00008806 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008807 TemplateParameterLists.size(),
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00008808 (TemplateParameterList**) TemplateParameterLists.release());
8809 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00008810 }
8811 else
8812 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00008813 }
8814
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00008815 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8816 // Add alignment attributes if necessary; these attributes are checked when
8817 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008818 //
8819 // It is important for implementing the correct semantics that this
8820 // happen here (in act on tag decl). The #pragma pack stack is
8821 // maintained as a result of parser callbacks which can occur at
8822 // many points during the parsing of a struct declaration (because
8823 // the #pragma tokens are effectively skipped over during the
8824 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00008825 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +00008826
8827 AddMsStructLayoutForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008828 }
8829
Douglas Gregor21823bf2011-12-20 18:11:52 +00008830 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00008831 if (isExplicitSpecialization)
8832 Diag(New->getLocation(), diag::err_module_private_specialization)
8833 << 2
8834 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +00008835 // __module_private__ does not apply to local classes. However, we only
8836 // diagnose this as an error when the declaration specifiers are
8837 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +00008838 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +00008839 New->setModulePrivate();
8840 }
8841
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008842 // If this is a specialization of a member class (of a class template),
8843 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00008844 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00008845 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00008846
Douglas Gregordee1be82009-01-17 00:42:38 +00008847 if (Invalid)
8848 New->setInvalidDecl();
8849
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008850 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00008851 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008852
Douglas Gregordee1be82009-01-17 00:42:38 +00008853 // If we're declaring or defining a tag in function prototype scope
8854 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008855 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +00008856 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8857
Douglas Gregorc811d8f2008-12-15 16:32:14 +00008858 // Set the lexical context. If the tag has a C++ scope specifier, the
8859 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00008860 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00008861
John McCallaa74a0c2009-08-28 07:59:38 +00008862 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00008863 // In Microsoft mode, a friend declaration also acts as a forward
8864 // declaration so we always pass true to setObjectOfFriendDecl to make
8865 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00008866 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00008867 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00008868 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +00008869
Anders Carlsson5558ca12009-03-26 01:19:02 +00008870 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00008871 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00008872 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00008873
John McCall9bb74a52009-07-31 02:45:11 +00008874 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00008875 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00008876
Chris Lattner18b19622007-01-22 07:39:13 +00008877 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00008878 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00008879 // We might be replacing an existing declaration in the lookup tables;
8880 // if so, borrow its access specifier.
8881 if (PrevDecl)
8882 New->setAccess(PrevDecl->getAccess());
8883
Sebastian Redl50c68252010-08-31 00:36:30 +00008884 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00008885 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +00008886 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00008887 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8888 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00008889 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00008890 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008891 PushOnScopeChains(New, S, !IsForwardReference);
8892 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +00008893 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008894
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00008895 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008896 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00008897 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00008898
Douglas Gregor27821ce2009-07-07 16:35:42 +00008899 // If this is the C FILE type, notify the AST context.
8900 if (IdentifierInfo *II = New->getIdentifier())
8901 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008902 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00008903 II->isStr("FILE"))
8904 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00008905
James Molloy6f8780b2012-02-29 10:24:19 +00008906 // If we were in function prototype scope (and not in C++ mode), add this
8907 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008908 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +00008909 InFunctionDeclarator && Name)
8910 DeclsInPrototypeScope.push_back(New);
8911
Rafael Espindolac67f2232012-05-10 02:50:16 +00008912 if (PrevDecl)
8913 mergeDeclAttributes(New, PrevDecl);
8914
Douglas Gregord6ab8742009-05-28 23:31:59 +00008915 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00008916 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00008917}
Chris Lattner1300fb92007-01-23 23:42:53 +00008918
John McCall48871652010-08-21 09:40:31 +00008919void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008920 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008921 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00008922
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008923 // Enter the tag context.
8924 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008925
8926 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +00008927
8928 // If there's a #pragma GCC visibility in scope, set the visibility of this
8929 // record.
8930 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00008931}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008932
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008933Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008934 assert(isa<ObjCContainerDecl>(IDecl) &&
8935 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8936 DeclContext *OCD = cast<DeclContext>(IDecl);
8937 assert(getContainingDC(OCD) == CurContext &&
8938 "The next DeclContext should be lexically contained in the current one.");
8939 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00008940 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00008941}
8942
John McCall48871652010-08-21 09:40:31 +00008943void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00008944 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00008945 SourceLocation LBraceLoc) {
8946 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008947 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008948
John McCall1c7e6ec2009-12-20 07:58:13 +00008949 FieldCollector->StartClass();
8950
8951 if (!Record->getIdentifier())
8952 return;
8953
Anders Carlsson30f29442011-03-25 14:31:08 +00008954 if (FinalLoc.isValid())
8955 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00008956
John McCall1c7e6ec2009-12-20 07:58:13 +00008957 // C++ [class]p2:
8958 // [...] The class-name is also inserted into the scope of the
8959 // class itself; this is known as the injected-class-name. For
8960 // purposes of access checking, the injected-class-name is treated
8961 // as if it were a public member name.
8962 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00008963 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8964 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00008965 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00008966 /*PrevDecl=*/0,
8967 /*DelayTypeCreation=*/true);
8968 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00008969 InjectedClassName->setImplicit();
8970 InjectedClassName->setAccess(AS_public);
8971 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8972 InjectedClassName->setDescribedClassTemplate(Template);
8973 PushOnScopeChains(InjectedClassName, S);
8974 assert(InjectedClassName->isInjectedClassName() &&
8975 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008976}
8977
John McCall48871652010-08-21 09:40:31 +00008978void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00008979 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00008980 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00008981 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00008982 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008983
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00008984 // Make sure we "complete" the definition even it is invalid.
8985 if (Tag->isBeingDefined()) {
8986 assert(Tag->isInvalidDecl() && "We should already have completed it");
8987 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8988 RD->completeDefinition();
8989 }
8990
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008991 if (isa<CXXRecordDecl>(Tag))
8992 FieldCollector->FinishClass();
8993
8994 // Exit this scope of this tag's definition.
8995 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00008996
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008997 // Notify the consumer that we've defined a tag.
8998 Consumer.HandleTagDeclDefinition(Tag);
8999}
Chris Lattner535b8302008-06-21 19:39:06 +00009000
Fariborz Jahanian4327b322011-08-29 17:33:12 +00009001void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009002 // Exit this scope of this interface definition.
9003 PopDeclContext();
9004}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009005
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +00009006void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +00009007 assert(DC == CurContext && "Mismatch of container contexts");
9008 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009009 ActOnObjCContainerFinishDefinition();
9010}
9011
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +00009012void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
9013 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00009014 OriginalLexicalContext = 0;
9015}
9016
John McCall48871652010-08-21 09:40:31 +00009017void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00009018 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00009019 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00009020 Tag->setInvalidDecl();
9021
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00009022 // Make sure we "complete" the definition even it is invalid.
9023 if (Tag->isBeingDefined()) {
9024 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9025 RD->completeDefinition();
9026 }
9027
John McCall71ba5f22010-03-17 19:25:57 +00009028 // We're undoing ActOnTagStartDefinition here, not
9029 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
9030 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00009031
9032 PopDeclContext();
9033}
9034
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009035// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +00009036ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
9037 IdentifierInfo *FieldName,
9038 QualType FieldTy, Expr *BitWidth,
9039 bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +00009040 // Default to true; that shouldn't confuse checks for emptiness
9041 if (ZeroWidth)
9042 *ZeroWidth = true;
9043
Chris Lattner73bf7b42009-03-05 22:45:59 +00009044 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00009045 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00009046 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00009047 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00009048 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +00009049 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009050 if (FieldName)
9051 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
9052 << FieldName << FieldTy << BitWidth->getSourceRange();
9053 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
9054 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00009055 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
9056 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +00009057 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +00009058
9059 // If the bit-width is type- or value-dependent, don't try to check
9060 // it now.
9061 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +00009062 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009063
Anders Carlsson5df391e2008-12-06 20:33:04 +00009064 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00009065 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
9066 if (ICE.isInvalid())
9067 return ICE;
9068 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +00009069
Eli Friedmanc96d4962009-08-15 21:55:26 +00009070 if (Value != 0 && ZeroWidth)
9071 *ZeroWidth = false;
9072
Chris Lattner81ed6802008-12-12 04:56:04 +00009073 // Zero-width bitfield is ok for anonymous field.
9074 if (Value == 0 && FieldName)
9075 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00009076
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009077 if (Value.isSigned() && Value.isNegative()) {
9078 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00009079 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009080 << FieldName << Value.toString(10);
9081 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
9082 << Value.toString(10);
9083 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009084
Douglas Gregor1efa4372009-03-11 18:59:21 +00009085 if (!FieldTy->isDependentType()) {
9086 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009087 if (Value.getZExtValue() > TypeSize) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009088 if (!getLangOpts().CPlusPlus) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00009089 if (FieldName)
9090 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
9091 << FieldName << (unsigned)Value.getZExtValue()
9092 << (unsigned)TypeSize;
9093
9094 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
9095 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9096 }
9097
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009098 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00009099 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
9100 << FieldName << (unsigned)Value.getZExtValue()
9101 << (unsigned)TypeSize;
9102 else
9103 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
9104 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00009105 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00009106 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009107
Richard Smithf4c51d92012-02-04 09:53:13 +00009108 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +00009109}
9110
Richard Smith938f40b2011-06-11 17:19:42 +00009111/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00009112/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00009113Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00009114 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00009115 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00009116 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +00009117 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +00009118 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00009119}
9120
9121/// HandleField - Analyze a field of a C struct or a C++ data member.
9122///
9123FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
9124 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +00009125 Declarator &D, Expr *BitWidth,
9126 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009127 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00009128 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00009129 SourceLocation Loc = DeclStart;
9130 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00009131
John McCall8cb7bdf2010-06-04 23:28:52 +00009132 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9133 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009134 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00009135 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00009136
Douglas Gregora02a72a2010-12-15 23:18:36 +00009137 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9138 UPPC_DataMemberType)) {
9139 D.setInvalidType();
9140 T = Context.IntTy;
9141 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
9142 }
9143 }
9144
Eli Friedman574c7452009-04-07 19:37:57 +00009145 DiagnoseFunctionSpecifiers(D);
9146
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009147 if (D.getDeclSpec().isThreadSpecified())
9148 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Richard Smitha77a0a62011-08-15 21:04:07 +00009149 if (D.getDeclSpec().isConstexprSpecified())
9150 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
9151 << 2;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00009152
9153 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +00009154 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +00009155 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
9156 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +00009157 switch (Previous.getResultKind()) {
9158 case LookupResult::Found:
9159 case LookupResult::FoundUnresolvedValue:
9160 PrevDecl = Previous.getAsSingle<NamedDecl>();
9161 break;
9162
9163 case LookupResult::FoundOverloaded:
9164 PrevDecl = Previous.getRepresentativeDecl();
9165 break;
9166
9167 case LookupResult::NotFound:
9168 case LookupResult::NotFoundInCurrentInstantiation:
9169 case LookupResult::Ambiguous:
9170 break;
9171 }
9172 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +00009173
9174 if (PrevDecl && PrevDecl->isTemplateParameter()) {
9175 // Maybe we will complain about the shadowed template parameter.
9176 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9177 // Just pretend that we didn't see the previous declaration.
9178 PrevDecl = 0;
9179 }
9180
Douglas Gregor1efa4372009-03-11 18:59:21 +00009181 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
9182 PrevDecl = 0;
9183
Steve Naroff5ec6ff72009-07-14 14:58:18 +00009184 bool Mutable
9185 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009186 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +00009187 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +00009188 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +00009189 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00009190
9191 if (NewFD->isInvalidDecl())
9192 Record->setInvalidDecl();
9193
Douglas Gregor3baa6702011-09-12 16:11:24 +00009194 if (D.getDeclSpec().isModulePrivateSpecified())
9195 NewFD->setModulePrivate();
9196
Douglas Gregor1efa4372009-03-11 18:59:21 +00009197 if (NewFD->isInvalidDecl() && PrevDecl) {
9198 // Don't introduce NewFD into scope; there's already something
9199 // with the same name in the same scope.
9200 } else if (II) {
9201 PushOnScopeChains(NewFD, S);
9202 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009203 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009204
9205 return NewFD;
9206}
9207
9208/// \brief Build a new FieldDecl and check its well-formedness.
9209///
9210/// This routine builds a new FieldDecl given the fields name, type,
9211/// record, etc. \p PrevDecl should refer to any previous declaration
9212/// with the same name and in the same scope as the field to be
9213/// created.
9214///
9215/// \returns a new FieldDecl.
9216///
Mike Stump11289f42009-09-09 15:08:12 +00009217/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00009218FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00009219 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00009220 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +00009221 bool Mutable, Expr *BitWidth,
9222 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00009223 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009224 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00009225 Declarator *D) {
9226 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00009227 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009228 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009229
Douglas Gregor1efa4372009-03-11 18:59:21 +00009230 // If we receive a broken type, recover by assuming 'int' and
9231 // marking this declaration as invalid.
9232 if (T.isNull()) {
9233 InvalidDecl = true;
9234 T = Context.IntTy;
9235 }
9236
Eli Friedmand0e8de22009-12-07 00:22:08 +00009237 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00009238 if (!EltTy->isDependentType()) {
9239 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9240 // Fields of incomplete type force their record to be invalid.
9241 Record->setInvalidDecl();
9242 InvalidDecl = true;
9243 } else {
9244 NamedDecl *Def;
9245 EltTy->isIncompleteType(&Def);
9246 if (Def && Def->isInvalidDecl()) {
9247 Record->setInvalidDecl();
9248 InvalidDecl = true;
9249 }
9250 }
John McCall2677e102010-08-16 23:42:35 +00009251 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00009252
Steve Naroff8eeeb132007-05-08 21:09:37 +00009253 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9254 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00009255 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00009256 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009257 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00009258 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009259 SizeIsNegative,
9260 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009261 if (!FixedTy.isNull()) {
9262 Diag(Loc, diag::warn_illegal_constant_array_size);
9263 T = FixedTy;
9264 } else {
9265 if (SizeIsNegative)
9266 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00009267 else if (Oversized.getBoolValue())
9268 Diag(Loc, diag::err_array_too_large)
9269 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009270 else
9271 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00009272 InvalidDecl = true;
9273 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00009274 }
Mike Stump11289f42009-09-09 15:08:12 +00009275
Anders Carlsson576cc6f2009-03-22 20:18:17 +00009276 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00009277 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9278 diag::err_abstract_type_in_decl,
9279 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00009280 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00009281
Eli Friedmanc96d4962009-08-15 21:55:26 +00009282 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00009283 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +00009284 if (!InvalidDecl && BitWidth) {
9285 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9286 if (!BitWidth) {
9287 InvalidDecl = true;
9288 BitWidth = 0;
9289 ZeroWidth = false;
9290 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00009291 }
Mike Stump11289f42009-09-09 15:08:12 +00009292
John McCallb1cd7da2010-06-04 08:34:12 +00009293 // Check that 'mutable' is consistent with the type of the declaration.
9294 if (!InvalidDecl && Mutable) {
9295 unsigned DiagID = 0;
9296 if (T->isReferenceType())
9297 DiagID = diag::err_mutable_reference;
9298 else if (T.isConstQualified())
9299 DiagID = diag::err_mutable_const;
9300
9301 if (DiagID) {
9302 SourceLocation ErrLoc = Loc;
9303 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9304 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9305 Diag(ErrLoc, DiagID);
9306 Mutable = false;
9307 InvalidDecl = true;
9308 }
9309 }
9310
Abramo Bagnaradff19302011-03-08 08:55:46 +00009311 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00009312 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009313 if (InvalidDecl)
9314 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00009315
Douglas Gregor1efa4372009-03-11 18:59:21 +00009316 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9317 Diag(Loc, diag::err_duplicate_member) << II;
9318 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9319 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009320 }
9321
David Blaikiebbafb8a2012-03-11 07:00:24 +00009322 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00009323 if (Record->isUnion()) {
9324 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9325 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9326 if (RDecl->getDefinition()) {
9327 // C++ [class.union]p1: An object of a class with a non-trivial
9328 // constructor, a non-trivial copy constructor, a non-trivial
9329 // destructor, or a non-trivial copy assignment operator
9330 // cannot be a member of a union, nor can an array of such
9331 // objects.
Richard Smithf720df02011-10-19 20:41:51 +00009332 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00009333 NewFD->setInvalidDecl();
9334 }
9335 }
9336
9337 // C++ [class.union]p1: If a union contains a member of reference type,
9338 // the program is ill-formed.
9339 if (EltTy->isReferenceType()) {
9340 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9341 << NewFD->getDeclName() << EltTy;
9342 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00009343 }
9344 }
9345 }
9346
Douglas Gregor1efa4372009-03-11 18:59:21 +00009347 // FIXME: We need to pass in the attributes given an AST
9348 // representation, not a parser representation.
9349 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00009350 // FIXME: What to pass instead of TUScope?
9351 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00009352
John McCall31168b02011-06-15 23:02:42 +00009353 // In auto-retain/release, infer strong retension for fields of
9354 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009355 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +00009356 NewFD->setInvalidDecl();
9357
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00009358 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00009359 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00009360
Douglas Gregor4261e4c2009-03-11 20:50:30 +00009361 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00009362 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00009363}
9364
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009365bool Sema::CheckNontrivialField(FieldDecl *FD) {
9366 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009367 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009368
9369 if (FD->isInvalidDecl())
9370 return true;
9371
9372 QualType EltTy = Context.getBaseElementType(FD->getType());
9373 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9374 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9375 if (RDecl->getDefinition()) {
9376 // We check for copy constructors before constructors
9377 // because otherwise we'll never get complaints about
9378 // copy constructors.
9379
9380 CXXSpecialMember member = CXXInvalid;
9381 if (!RDecl->hasTrivialCopyConstructor())
9382 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00009383 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009384 member = CXXDefaultConstructor;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009385 else if (!RDecl->hasTrivialCopyAssignment())
9386 member = CXXCopyAssignment;
9387 else if (!RDecl->hasTrivialDestructor())
9388 member = CXXDestructor;
9389
9390 if (member != CXXInvalid) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009391 if (!getLangOpts().CPlusPlus0x &&
9392 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +00009393 // Objective-C++ ARC: it is an error to have a non-trivial field of
9394 // a union. However, system headers in Objective-C programs
9395 // occasionally have Objective-C lifetime objects within unions,
9396 // and rather than cause the program to fail, we make those
9397 // members unavailable.
9398 SourceLocation Loc = FD->getLocation();
9399 if (getSourceManager().isInSystemHeader(Loc)) {
9400 if (!FD->hasAttr<UnavailableAttr>())
9401 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009402 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00009403 return false;
9404 }
9405 }
Richard Smithf720df02011-10-19 20:41:51 +00009406
David Blaikiebbafb8a2012-03-11 07:00:24 +00009407 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
Richard Smithf720df02011-10-19 20:41:51 +00009408 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9409 diag::err_illegal_union_or_anon_struct_member)
9410 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009411 DiagnoseNontrivial(RT, member);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009412 return !getLangOpts().CPlusPlus0x;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00009413 }
9414 }
9415 }
9416
9417 return false;
9418}
9419
Richard Smith8e1c9322012-02-26 10:50:32 +00009420/// If the given constructor is user-provided, produce a diagnostic explaining
9421/// that it makes the class non-trivial.
9422static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9423 CXXConstructorDecl *CD,
9424 Sema::CXXSpecialMember CSM) {
9425 if (!CD->isUserProvided())
9426 return false;
9427
9428 SourceLocation CtorLoc = CD->getLocation();
9429 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9430 return true;
9431}
9432
Douglas Gregor8a273912009-07-22 18:25:24 +00009433/// DiagnoseNontrivial - Given that a class has a non-trivial
9434/// special member, figure out why.
9435void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9436 QualType QT(T, 0U);
9437 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9438
9439 // Check whether the member was user-declared.
9440 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00009441 case CXXInvalid:
9442 break;
9443
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009444 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00009445 if (RD->hasUserDeclaredConstructor()) {
9446 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Richard Smith8e1c9322012-02-26 10:50:32 +00009447 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
David Blaikie40ed2972012-06-06 20:45:41 +00009448 if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
Douglas Gregor8a273912009-07-22 18:25:24 +00009449 return;
Douglas Gregor8a273912009-07-22 18:25:24 +00009450
Richard Smith8e1c9322012-02-26 10:50:32 +00009451 // No user-provided constructors; look for constructor templates.
9452 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9453 tmpl_iter;
9454 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9455 TI != TE; ++TI) {
9456 CXXConstructorDecl *CD =
9457 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9458 if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9459 return;
9460 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009461 }
9462 break;
9463
9464 case CXXCopyConstructor:
9465 if (RD->hasUserDeclaredCopyConstructor()) {
9466 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00009467 RD->getCopyConstructor(0)->getLocation();
9468 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9469 return;
9470 }
9471 break;
9472
9473 case CXXMoveConstructor:
9474 if (RD->hasUserDeclaredMoveConstructor()) {
9475 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009476 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9477 return;
9478 }
9479 break;
9480
9481 case CXXCopyAssignment:
9482 if (RD->hasUserDeclaredCopyAssignment()) {
9483 // FIXME: this should use the location of the copy
9484 // assignment, not the type.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009485 SourceLocation TyLoc = RD->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009486 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9487 return;
9488 }
9489 break;
9490
Alexis Huntfcaeae42011-05-25 20:50:04 +00009491 case CXXMoveAssignment:
9492 if (RD->hasUserDeclaredMoveAssignment()) {
9493 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9494 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9495 return;
9496 }
9497 break;
9498
Douglas Gregor8a273912009-07-22 18:25:24 +00009499 case CXXDestructor:
9500 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00009501 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009502 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9503 return;
9504 }
9505 break;
9506 }
9507
9508 typedef CXXRecordDecl::base_class_iterator base_iter;
9509
9510 // Virtual bases and members inhibit trivial copying/construction,
9511 // but not trivial destruction.
9512 if (member != CXXDestructor) {
9513 // Check for virtual bases. vbases includes indirect virtual bases,
9514 // so we just iterate through the direct bases.
9515 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9516 if (bi->isVirtual()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009517 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009518 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9519 return;
9520 }
9521
9522 // Check for virtual methods.
9523 typedef CXXRecordDecl::method_iterator meth_iter;
9524 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9525 ++mi) {
9526 if (mi->isVirtual()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009527 SourceLocation MLoc = mi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009528 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9529 return;
9530 }
9531 }
9532 }
Mike Stump11289f42009-09-09 15:08:12 +00009533
Douglas Gregor8a273912009-07-22 18:25:24 +00009534 bool (CXXRecordDecl::*hasTrivial)() const;
9535 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009536 case CXXDefaultConstructor:
Alexis Huntf479f1b2011-05-09 18:22:59 +00009537 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00009538 case CXXCopyConstructor:
9539 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9540 case CXXCopyAssignment:
9541 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9542 case CXXDestructor:
9543 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9544 default:
David Blaikieaa347f92011-09-23 20:26:49 +00009545 llvm_unreachable("unexpected special member");
Douglas Gregor8a273912009-07-22 18:25:24 +00009546 }
9547
9548 // Check for nontrivial bases (and recurse).
9549 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009550 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00009551 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00009552 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9553 if (!(BaseRecTy->*hasTrivial)()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009554 SourceLocation BaseLoc = bi->getLocStart();
Douglas Gregor8a273912009-07-22 18:25:24 +00009555 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9556 DiagnoseNontrivial(BaseRT, member);
9557 return;
9558 }
9559 }
Mike Stump11289f42009-09-09 15:08:12 +00009560
Douglas Gregor8a273912009-07-22 18:25:24 +00009561 // Check for nontrivial members (and recurse).
9562 typedef RecordDecl::field_iterator field_iter;
9563 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9564 ++fi) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009565 QualType EltTy = Context.getBaseElementType(fi->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009566 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00009567 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9568
9569 if (!(EltRD->*hasTrivial)()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009570 SourceLocation FLoc = fi->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00009571 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9572 DiagnoseNontrivial(EltRT, member);
9573 return;
9574 }
9575 }
John McCall31168b02011-06-15 23:02:42 +00009576
9577 if (EltTy->isObjCLifetimeType()) {
9578 switch (EltTy.getObjCLifetime()) {
9579 case Qualifiers::OCL_None:
9580 case Qualifiers::OCL_ExplicitNone:
9581 break;
9582
9583 case Qualifiers::OCL_Autoreleasing:
9584 case Qualifiers::OCL_Weak:
9585 case Qualifiers::OCL_Strong:
David Blaikie2d7c57e2012-04-30 02:36:29 +00009586 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00009587 << QT << EltTy.getObjCLifetime();
9588 return;
9589 }
9590 }
Douglas Gregor8a273912009-07-22 18:25:24 +00009591 }
9592
David Blaikie83d382b2011-09-23 05:06:16 +00009593 llvm_unreachable("found no explanation for non-trivial member");
Douglas Gregor8a273912009-07-22 18:25:24 +00009594}
9595
Mike Stump11289f42009-09-09 15:08:12 +00009596/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00009597/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00009598static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00009599TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00009600 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +00009601 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +00009602 case tok::objc_private: return ObjCIvarDecl::Private;
9603 case tok::objc_public: return ObjCIvarDecl::Public;
9604 case tok::objc_protected: return ObjCIvarDecl::Protected;
9605 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00009606 }
9607}
9608
Mike Stump11289f42009-09-09 15:08:12 +00009609/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00009610/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00009611Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00009612 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +00009613 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +00009614 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00009615
Fariborz Jahaniande615832008-04-10 23:32:45 +00009616 IdentifierInfo *II = D.getIdentifier();
9617 Expr *BitWidth = (Expr*)BitfieldWidth;
9618 SourceLocation Loc = DeclStart;
9619 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00009620
Fariborz Jahaniande615832008-04-10 23:32:45 +00009621 // FIXME: Unnamed fields can be handled in various different ways, for
9622 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00009623
John McCall8cb7bdf2010-06-04 23:28:52 +00009624 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9625 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009626
Fariborz Jahaniande615832008-04-10 23:32:45 +00009627 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00009628 // 6.7.2.1p3, 6.7.2.1p4
Richard Smithf4c51d92012-02-04 09:53:13 +00009629 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9630 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009631 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00009632 } else {
9633 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00009634
Fariborz Jahaniande615832008-04-10 23:32:45 +00009635 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00009636
Fariborz Jahaniande615832008-04-10 23:32:45 +00009637 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00009638 if (T->isReferenceType()) {
9639 Diag(Loc, diag::err_ivar_reference_type);
9640 D.setInvalidType();
9641 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00009642 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9643 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00009644 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00009645 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009646 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00009647 }
Mike Stump11289f42009-09-09 15:08:12 +00009648
Ted Kremenek73295fa2008-07-23 18:04:17 +00009649 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00009650 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00009651 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9652 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00009653 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009654 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +00009655 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9656 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +00009657 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00009658 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00009659 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +00009660 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00009661 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00009662 EnclosingContext = IMPDecl->getClassInterface();
9663 assert(EnclosingContext && "Implementation has no class interface!");
9664 }
9665 else
9666 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009667 } else {
9668 if (ObjCCategoryDecl *CDecl =
9669 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +00009670 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009671 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00009672 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009673 }
9674 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00009675 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00009676 }
Mike Stump11289f42009-09-09 15:08:12 +00009677
Ted Kremenek73295fa2008-07-23 18:04:17 +00009678 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009679 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9680 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00009681 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00009682
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009683 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009684 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00009685 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00009686 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009687 && !isa<TagDecl>(PrevDecl)) {
9688 Diag(Loc, diag::err_duplicate_member) << II;
9689 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9690 NewID->setInvalidDecl();
9691 }
9692 }
9693
Ted Kremenek73295fa2008-07-23 18:04:17 +00009694 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00009695 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00009696
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009697 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00009698 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00009699
John McCall31168b02011-06-15 23:02:42 +00009700 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009701 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +00009702 NewID->setInvalidDecl();
9703
Douglas Gregor3baa6702011-09-12 16:11:24 +00009704 if (D.getDeclSpec().isModulePrivateSpecified())
9705 NewID->setModulePrivate();
9706
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009707 if (II) {
9708 // FIXME: When interfaces are DeclContexts, we'll need to add
9709 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00009710 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009711 IdResolver.AddDecl(NewID);
9712 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +00009713
John McCall5fb5df92012-06-20 06:18:46 +00009714 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +00009715 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +00009716 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +00009717
John McCall48871652010-08-21 09:40:31 +00009718 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00009719}
9720
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009721/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9722/// class and class extensions. For every class @interface and class
9723/// extension @interface, if the last ivar is a bitfield of any type,
9724/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009725void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009726 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +00009727 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009728 return;
9729
9730 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9731 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9732
Richard Smithcaf33902011-10-10 18:28:20 +00009733 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009734 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009735 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009736 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009737 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009738 if (!CD->IsClassExtension())
9739 return;
9740 }
9741 // No need to add this to end of @implementation.
9742 else
9743 return;
9744 }
9745 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +00009746 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9747 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009748
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00009749 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009750 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009751 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +00009752 Context.getTrivialTypeSourceInfo(Context.CharTy,
9753 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00009754 ObjCIvarDecl::Private, BW,
9755 true);
9756 AllIvarDecls.push_back(Ivar);
9757}
9758
Fariborz Jahanian343f7092007-09-29 00:54:24 +00009759void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00009760 SourceLocation RecLoc, Decl *EnclosingDecl,
David Blaikie751c5582011-09-22 02:58:26 +00009761 llvm::ArrayRef<Decl *> Fields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00009762 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00009763 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00009764 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00009765
Chris Lattnerd13b8b52009-02-23 22:00:08 +00009766 // If the decl this is being inserted into is invalid, then it may be a
9767 // redeclaration or some other bogus case. Don't try to add fields to it.
Douglas Gregor7bfedd62011-09-12 18:58:37 +00009768 if (EnclosingDecl->isInvalidDecl())
Chris Lattnerd13b8b52009-02-23 22:00:08 +00009769 return;
Mike Stump11289f42009-09-09 15:08:12 +00009770
Eli Friedmana7679412012-02-07 05:00:47 +00009771 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9772
9773 // Start counting up the number of named members; make sure to include
9774 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +00009775 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +00009776 if (Record) {
9777 for (RecordDecl::decl_iterator i = Record->decls_begin(),
9778 e = Record->decls_end(); i != e; i++) {
9779 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9780 if (IFD->getDeclName())
9781 ++NumNamedMembers;
9782 }
9783 }
9784
9785 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009786 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00009787
John McCall31168b02011-06-15 23:02:42 +00009788 bool ARCErrReported = false;
David Blaikie751c5582011-09-22 02:58:26 +00009789 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9790 i != end; ++i) {
9791 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +00009792
Chris Lattner720a0542007-01-25 00:44:24 +00009793 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00009794 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00009795
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009796 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00009797 // Remember all fields written by the user.
9798 RecFields.push_back(FD);
9799 }
Mike Stump11289f42009-09-09 15:08:12 +00009800
Chris Lattner73bf7b42009-03-05 22:45:59 +00009801 // If the field is already invalid for some reason, don't emit more
9802 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00009803 if (FD->isInvalidDecl()) {
9804 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00009805 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00009806 }
Mike Stump11289f42009-09-09 15:08:12 +00009807
Douglas Gregorac1fb652009-03-24 19:52:54 +00009808 // C99 6.7.2.1p2:
9809 // A structure or union shall not contain a member with
9810 // incomplete or function type (hence, a structure shall not
9811 // contain an instance of itself, but may contain a pointer to
9812 // an instance of itself), except that the last member of a
9813 // structure with more than one named member may have incomplete
9814 // array type; such a structure (and any union containing,
9815 // possibly recursively, a member that is such a structure)
9816 // shall not be a member of a structure or an element of an
9817 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00009818 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00009819 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00009820 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009821 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00009822 FD->setInvalidDecl();
9823 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00009824 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00009825 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +00009826 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00009827 ((getLangOpts().MicrosoftExt ||
9828 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +00009829 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00009830 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009831 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00009832 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00009833 // as the sole element of a struct/class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009834 if (getLangOpts().MicrosoftExt) {
Francois Pichetf657b632010-09-15 00:14:08 +00009835 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009836 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00009837 << FD->getDeclName();
David Blaikie751c5582011-09-22 02:58:26 +00009838 else if (Fields.size() == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009839 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00009840 << FD->getDeclName() << Record->getTagKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009841 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009842 if (Record->isUnion())
9843 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9844 << FD->getDeclName();
David Blaikie751c5582011-09-22 02:58:26 +00009845 else if (Fields.size() == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009846 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9847 << FD->getDeclName() << Record->getTagKind();
David Chisnall07518f22012-03-16 12:15:37 +00009848 } else if (!getLangOpts().C99) {
9849 if (Record->isUnion())
9850 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9851 << FD->getDeclName();
9852 else
9853 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
9854 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00009855 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009856 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009857 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00009858 FD->setInvalidDecl();
9859 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00009860 continue;
9861 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009862 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +00009863 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009864 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00009865 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009866 FD->setInvalidDecl();
9867 EnclosingDecl->setInvalidDecl();
9868 continue;
9869 }
Chris Lattner720a0542007-01-25 00:44:24 +00009870 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00009871 if (Record)
9872 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00009873 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00009874 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00009875 diag::err_field_incomplete)) {
9876 // Incomplete type
9877 FD->setInvalidDecl();
9878 EnclosingDecl->setInvalidDecl();
9879 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009880 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00009881 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9882 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00009883 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00009884 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00009885 } else {
9886 // If this is a struct/class and this is not the last element, reject
9887 // it. Note that GCC supports variable sized arrays in the middle of
9888 // structures.
David Blaikie751c5582011-09-22 02:58:26 +00009889 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00009890 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00009891 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00009892 else {
9893 // We support flexible arrays at the end of structs in
9894 // other structs as an extension.
9895 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9896 << FD->getDeclName();
9897 if (Record)
9898 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00009899 }
Chris Lattner720a0542007-01-25 00:44:24 +00009900 }
9901 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00009902 if (Record && FDTTy->getDecl()->hasObjectMember())
9903 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00009904 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00009905 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009906 Diag(FD->getLocation(), diag::err_statically_allocated_object)
9907 << FixItHint::CreateInsertion(FD->getLocation(), "*");
9908 QualType T = Context.getObjCObjectPointerType(FD->getType());
9909 FD->setType(T);
John McCall31168b02011-06-15 23:02:42 +00009910 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00009911 else if (!getLangOpts().CPlusPlus) {
9912 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
John McCall31168b02011-06-15 23:02:42 +00009913 // It's an error in ARC if a field has lifetime.
9914 // We don't want to report this in a system header, though,
9915 // so we just make the field unavailable.
9916 // FIXME: that's really not sufficient; we need to make the type
9917 // itself invalid to, say, initialize or copy.
9918 QualType T = FD->getType();
9919 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9920 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9921 SourceLocation loc = FD->getLocation();
9922 if (getSourceManager().isInSystemHeader(loc)) {
9923 if (!FD->hasAttr<UnavailableAttr>()) {
9924 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009925 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00009926 }
9927 } else {
Fariborz Jahanianb989e6e2011-12-12 23:17:04 +00009928 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
9929 << T->isBlockPointerType();
John McCall31168b02011-06-15 23:02:42 +00009930 }
9931 ARCErrReported = true;
9932 }
9933 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00009934 else if (getLangOpts().ObjC1 &&
9935 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +00009936 Record && !Record->hasObjectMember()) {
9937 if (FD->getType()->isObjCObjectPointerType() ||
9938 FD->getType().isObjCGCStrong())
9939 Record->setHasObjectMember(true);
9940 else if (Context.getAsArrayType(FD->getType())) {
9941 QualType BaseType = Context.getBaseElementType(FD->getType());
9942 if (BaseType->isRecordType() &&
9943 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9944 Record->setHasObjectMember(true);
9945 else if (BaseType->isObjCObjectPointerType() ||
9946 BaseType.isObjCGCStrong())
9947 Record->setHasObjectMember(true);
9948 }
9949 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +00009950 }
Chris Lattner82625602007-01-24 02:26:21 +00009951 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00009952 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00009953 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00009954 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009955
Chris Lattner82625602007-01-24 02:26:21 +00009956 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00009957 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00009958 bool Completed = false;
9959 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9960 if (!CXXRecord->isInvalidDecl()) {
9961 // Set access bits correctly on the directly-declared conversions.
9962 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9963 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9964 I != E; ++I)
9965 Convs->setAccess(I, (*I)->getAccess());
9966
9967 if (!CXXRecord->isDependentType()) {
John McCall31168b02011-06-15 23:02:42 +00009968 // Objective-C Automatic Reference Counting:
9969 // If a class has a non-static data member of Objective-C pointer
9970 // type (or array thereof), it is a non-POD type and its
9971 // default constructor (if any), copy constructor, copy assignment
9972 // operator, and destructor are non-trivial.
9973 //
9974 // This rule is also handled by CXXRecordDecl::completeDefinition().
9975 // However, here we check whether this particular class is only
9976 // non-POD because of the presence of an Objective-C pointer member.
9977 // If so, objects of this type cannot be shared between code compiled
9978 // with instant objects and code compiled with manual retain/release.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009979 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009980 CXXRecord->hasObjectMember() &&
9981 CXXRecord->getLinkage() == ExternalLinkage) {
9982 if (CXXRecord->isPOD()) {
9983 Diag(CXXRecord->getLocation(),
9984 diag::warn_arc_non_pod_class_with_object_member)
9985 << CXXRecord;
9986 } else {
9987 // FIXME: Fix-Its would be nice here, but finding a good location
9988 // for them is going to be tricky.
9989 if (CXXRecord->hasTrivialCopyConstructor())
9990 Diag(CXXRecord->getLocation(),
9991 diag::warn_arc_trivial_member_function_with_object_member)
9992 << CXXRecord << 0;
9993 if (CXXRecord->hasTrivialCopyAssignment())
9994 Diag(CXXRecord->getLocation(),
9995 diag::warn_arc_trivial_member_function_with_object_member)
9996 << CXXRecord << 1;
9997 if (CXXRecord->hasTrivialDestructor())
9998 Diag(CXXRecord->getLocation(),
9999 diag::warn_arc_trivial_member_function_with_object_member)
10000 << CXXRecord << 2;
10001 }
10002 }
10003
Sebastian Redl623ea822011-05-19 05:13:44 +000010004 // Adjust user-defined destructor exception spec.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010005 if (getLangOpts().CPlusPlus0x &&
Sebastian Redl623ea822011-05-19 05:13:44 +000010006 CXXRecord->hasUserDeclaredDestructor())
10007 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10008
Douglas Gregor8fb95122010-09-29 00:15:42 +000010009 // Add any implicitly-declared members to this class.
10010 AddImplicitlyDeclaredMembersToClass(CXXRecord);
10011
10012 // If we have virtual base classes, we may end up finding multiple
10013 // final overriders for a given virtual function. Check for this
10014 // problem now.
10015 if (CXXRecord->getNumVBases()) {
10016 CXXFinalOverriderMap FinalOverriders;
10017 CXXRecord->getFinalOverriders(FinalOverriders);
10018
10019 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10020 MEnd = FinalOverriders.end();
10021 M != MEnd; ++M) {
10022 for (OverridingMethods::iterator SO = M->second.begin(),
10023 SOEnd = M->second.end();
10024 SO != SOEnd; ++SO) {
10025 assert(SO->second.size() > 0 &&
10026 "Virtual function without overridding functions?");
10027 if (SO->second.size() == 1)
10028 continue;
10029
10030 // C++ [class.virtual]p2:
10031 // In a derived class, if a virtual member function of a base
10032 // class subobject has more than one final overrider the
10033 // program is ill-formed.
10034 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
10035 << (NamedDecl *)M->first << Record;
10036 Diag(M->first->getLocation(),
10037 diag::note_overridden_virtual_function);
10038 for (OverridingMethods::overriding_iterator
10039 OM = SO->second.begin(),
10040 OMEnd = SO->second.end();
10041 OM != OMEnd; ++OM)
10042 Diag(OM->Method->getLocation(), diag::note_final_overrider)
10043 << (NamedDecl *)M->first << OM->Method->getParent();
10044
10045 Record->setInvalidDecl();
10046 }
10047 }
10048 CXXRecord->completeDefinition(&FinalOverriders);
10049 Completed = true;
10050 }
10051 }
10052 }
10053 }
10054
10055 if (!Completed)
10056 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000010057
Chris Lattner622c1932008-02-06 00:51:33 +000010058 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000010059 ObjCIvarDecl **ClsFields =
10060 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000010061 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000010062 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000010063 // Add ivar's to class's DeclContext.
10064 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10065 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010066 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000010067 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000010068 // Must enforce the rule that ivars in the base classes may not be
10069 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000010070 if (ID->getSuperClass())
10071 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000010072 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000010073 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000010074 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000010075 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
10076 // Ivar declared in @implementation never belongs to the implementation.
10077 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000010078 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000010079 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000010080 IMPDecl->setIvarLBraceLoc(LBrac);
10081 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000010082 } else if (ObjCCategoryDecl *CDecl =
10083 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010084 // case of ivars in class extension; all other cases have been
10085 // reported as errors elsewhere.
10086 // FIXME. Class extension does not have a LocEnd field.
10087 // CDecl->setLocEnd(RBrac);
10088 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000010089 // Diagnose redeclaration of private ivars.
10090 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010091 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000010092 if (IDecl) {
10093 if (const ObjCIvarDecl *ClsIvar =
10094 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10095 Diag(ClsFields[i]->getLocation(),
10096 diag::err_duplicate_ivar_declaration);
10097 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
10098 continue;
10099 }
10100 for (const ObjCCategoryDecl *ClsExtDecl =
10101 IDecl->getFirstClassExtension();
10102 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
10103 if (const ObjCIvarDecl *ClsExtIvar =
10104 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10105 Diag(ClsFields[i]->getLocation(),
10106 diag::err_duplicate_ivar_declaration);
10107 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
10108 continue;
10109 }
10110 }
10111 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000010112 ClsFields[i]->setLexicalDeclContext(CDecl);
10113 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000010114 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000010115 CDecl->setIvarLBraceLoc(LBrac);
10116 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000010117 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000010118 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000010119
10120 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000010121 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000010122}
10123
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010124/// \brief Determine whether the given integral value is representable within
10125/// the given type T.
10126static bool isRepresentableIntegerValue(ASTContext &Context,
10127 llvm::APSInt &Value,
10128 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000010129 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000010130 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010131
Douglas Gregor0bf31402010-10-08 23:50:27 +000010132 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010133 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000010134 --BitWidth;
10135 return Value.getActiveBits() <= BitWidth;
10136 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010137 return Value.getMinSignedBits() <= BitWidth;
10138}
10139
10140// \brief Given an integral type, return the next larger integral type
10141// (or a NULL type of no such type exists).
10142static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
10143 // FIXME: Int128/UInt128 support, which also needs to be introduced into
10144 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000010145 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010146 const unsigned NumTypes = 4;
10147 QualType SignedIntegralTypes[NumTypes] = {
10148 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
10149 };
10150 QualType UnsignedIntegralTypes[NumTypes] = {
10151 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
10152 Context.UnsignedLongLongTy
10153 };
10154
10155 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010156 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
10157 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010158 for (unsigned I = 0; I != NumTypes; ++I)
10159 if (Context.getTypeSize(Types[I]) > BitWidth)
10160 return Types[I];
10161
10162 return QualType();
10163}
10164
Douglas Gregor954f6b272009-03-17 19:05:46 +000010165EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
10166 EnumConstantDecl *LastEnumConst,
10167 SourceLocation IdLoc,
10168 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000010169 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010170 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010171 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000010172 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010173
10174 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
10175 Val = 0;
10176
Eli Friedman7c6515a2011-12-06 00:10:34 +000010177 if (Val)
10178 Val = DefaultLvalueConversion(Val).take();
10179
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010180 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000010181 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010182 EltTy = Context.DependentTy;
10183 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010184 SourceLocation ExpLoc;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010185 if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
10186 !getLangOpts().MicrosoftMode) {
Richard Smithf8379a02012-01-18 23:55:52 +000010187 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
10188 // constant-expression in the enumerator-definition shall be a converted
10189 // constant expression of the underlying type.
10190 EltTy = Enum->getIntegerType();
10191 ExprResult Converted =
10192 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
10193 CCEK_Enumerator);
10194 if (Converted.isInvalid())
10195 Val = 0;
10196 else
10197 Val = Converted.take();
10198 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000010199 !(Val = VerifyIntegerConstantExpression(Val,
10200 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000010201 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000010202 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010203 if (Enum->isFixed()) {
10204 EltTy = Enum->getIntegerType();
10205
Richard Smithf8379a02012-01-18 23:55:52 +000010206 // In Obj-C and Microsoft mode, require the enumeration value to be
10207 // representable in the underlying type of the enumeration. In C++11,
10208 // we perform a non-narrowing conversion as part of converted constant
10209 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000010210 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010211 if (getLangOpts().MicrosoftMode) {
Francois Picheta3108062010-10-18 15:01:13 +000010212 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000010213 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000010214 } else
10215 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000010216 } else
John Wiegley01296292011-04-08 18:41:53 +000010217 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010218 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000010219 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000010220 // If the underlying type is not fixed, the type of each enumerator
10221 // is the type of its initializing value:
10222 // - If an initializer is specified for an enumerator, the
10223 // initializing value has the same type as the expression.
10224 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000010225 } else {
10226 // C99 6.7.2.2p2:
10227 // The expression that defines the value of an enumeration constant
10228 // shall be an integer constant expression that has a value
10229 // representable as an int.
10230
10231 // Complain if the value is not representable in an int.
10232 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10233 Diag(IdLoc, diag::ext_enum_value_not_int)
10234 << EnumVal.toString(10) << Val->getSourceRange()
10235 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10236 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10237 // Force the type of the expression to 'int'.
10238 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10239 }
10240 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010241 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010242 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000010243 }
10244 }
Mike Stump11289f42009-09-09 15:08:12 +000010245
Douglas Gregor954f6b272009-03-17 19:05:46 +000010246 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000010247 if (Enum->isDependentType())
10248 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010249 else if (!LastEnumConst) {
10250 // C++0x [dcl.enum]p5:
10251 // If the underlying type is not fixed, the type of each enumerator
10252 // is the type of its initializing value:
10253 // - If no initializer is specified for the first enumerator, the
10254 // initializing value has an unspecified integral type.
10255 //
10256 // GCC uses 'int' for its unspecified integral type, as does
10257 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000010258 if (Enum->isFixed()) {
10259 EltTy = Enum->getIntegerType();
10260 }
10261 else {
10262 EltTy = Context.IntTy;
10263 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010264 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000010265 // Assign the last value + 1.
10266 EnumVal = LastEnumConst->getInitVal();
10267 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010268 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000010269
10270 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010271 if (EnumVal < LastEnumConst->getInitVal()) {
10272 // C++0x [dcl.enum]p5:
10273 // If the underlying type is not fixed, the type of each enumerator
10274 // is the type of its initializing value:
10275 //
10276 // - Otherwise the type of the initializing value is the same as
10277 // the type of the initializing value of the preceding enumerator
10278 // unless the incremented value is not representable in that type,
10279 // in which case the type is an unspecified integral type
10280 // sufficient to contain the incremented value. If no such type
10281 // exists, the program is ill-formed.
10282 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010283 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010284 // There is no integral type larger enough to represent this
10285 // value. Complain, then allow the value to wrap around.
10286 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000010287 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010288 ++EnumVal;
10289 if (Enum->isFixed())
10290 // When the underlying type is fixed, this is ill-formed.
10291 Diag(IdLoc, diag::err_enumerator_wrapped)
10292 << EnumVal.toString(10)
10293 << EltTy;
10294 else
10295 Diag(IdLoc, diag::warn_enumerator_too_large)
10296 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010297 } else {
10298 EltTy = T;
10299 }
10300
10301 // Retrieve the last enumerator's value, extent that type to the
10302 // type that is supposed to be large enough to represent the incremented
10303 // value, then increment.
10304 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010305 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000010306 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010307 ++EnumVal;
10308
10309 // If we're not in C++, diagnose the overflow of enumerator values,
10310 // which in C99 means that the enumerator value is not representable in
10311 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10312 // permits enumerator values that are representable in some larger
10313 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010314 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010315 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010316 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010317 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10318 // Enforce C99 6.7.2.2p2 even when we compute the next value.
10319 Diag(IdLoc, diag::ext_enum_value_not_int)
10320 << EnumVal.toString(10) << 1;
10321 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000010322 }
10323 }
Mike Stump11289f42009-09-09 15:08:12 +000010324
Douglas Gregordc70c3a2010-03-02 17:53:14 +000010325 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010326 // Make the enumerator value match the signedness and size of the
10327 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000010328 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010329 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010330 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000010331
Douglas Gregor954f6b272009-03-17 19:05:46 +000010332 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000010333 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000010334}
10335
10336
John McCall811a0f52010-10-22 23:36:17 +000010337Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10338 SourceLocation IdLoc, IdentifierInfo *Id,
10339 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000010340 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000010341 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000010342 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000010343 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000010344
Chris Lattner1a76a3c2007-08-26 06:24:45 +000010345 // The scope passed in may not be a decl scope. Zip up the scope tree until
10346 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000010347 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000010348
Chris Lattner8116d1b2007-01-25 22:38:29 +000010349 // Verify that there isn't already something declared with this name in this
10350 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010351 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000010352 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000010353 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010354 // Maybe we will complain about the shadowed template parameter.
10355 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10356 // Just pretend that we didn't see the previous declaration.
10357 PrevDecl = 0;
10358 }
10359
10360 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000010361 // When in C++, we may get a TagDecl with the same name; in this case the
10362 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010363 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000010364 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000010365 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000010366 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010367 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000010368 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010369 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000010370 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000010371 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000010372 }
10373 }
Chris Lattner4ef40012007-06-11 01:28:17 +000010374
Douglas Gregor36c22a22010-10-15 13:21:21 +000010375 // C++ [class.mem]p13:
10376 // If T is the name of a class, then each of the following shall have a
10377 // name different from T:
10378 // - every enumerator of every member of class T that is an enumerated
10379 // type
10380 if (CXXRecordDecl *Record
10381 = dyn_cast<CXXRecordDecl>(
10382 TheEnumDecl->getDeclContext()->getRedeclContext()))
10383 if (Record->getIdentifier() && Record->getIdentifier() == Id)
10384 Diag(IdLoc, diag::err_member_name_of_class) << Id;
10385
John McCall811a0f52010-10-22 23:36:17 +000010386 EnumConstantDecl *New =
10387 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000010388
John McCall553c0792010-01-23 00:46:32 +000010389 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000010390 // Process attributes.
10391 if (Attr) ProcessDeclAttributeList(S, New, Attr);
10392
10393 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000010394 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000010395 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000010396 }
Douglas Gregor2f521192008-12-17 02:04:30 +000010397
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000010398 ActOnDocumentableDecl(New);
10399
John McCall48871652010-08-21 09:40:31 +000010400 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000010401}
10402
Richard Trieu01cf0932012-05-30 01:01:11 +000010403// Emits a warning if every element in the enum is the same value and if
10404// every element is initialized with a integer or boolean literal.
10405static void CheckForUniqueEnumValues(Sema &S, Decl **Elements,
10406 unsigned NumElements, EnumDecl *Enum,
10407 QualType EnumType) {
10408 if (S.Diags.getDiagnosticLevel(diag::warn_identical_enum_values,
10409 Enum->getLocation()) ==
10410 DiagnosticsEngine::Ignored)
10411 return;
10412
10413 if (NumElements < 2)
10414 return;
10415
David Blaikie7e6ad462012-05-30 20:45:14 +000010416 if (!Enum->getIdentifier())
10417 return;
10418
Richard Trieu01cf0932012-05-30 01:01:11 +000010419 llvm::APSInt FirstVal;
10420
10421 for (unsigned i = 0; i != NumElements; ++i) {
10422 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10423 if (!ECD)
10424 return;
10425
10426 Expr *InitExpr = ECD->getInitExpr();
10427 if (!InitExpr)
10428 return;
10429 InitExpr = InitExpr->IgnoreImpCasts();
10430 if (!isa<IntegerLiteral>(InitExpr) && !isa<CXXBoolLiteralExpr>(InitExpr))
10431 return;
10432
10433 if (i == 0) {
10434 FirstVal = ECD->getInitVal();
10435 continue;
10436 }
10437
10438 if (FirstVal != ECD->getInitVal())
10439 return;
10440 }
10441
Richard Trieu01cf0932012-05-30 01:01:11 +000010442 S.Diag(Enum->getLocation(), diag::warn_identical_enum_values)
David Blaikie7e6ad462012-05-30 20:45:14 +000010443 << EnumType << FirstVal.toString(10)
Richard Trieu01cf0932012-05-30 01:01:11 +000010444 << Enum->getSourceRange();
Richard Trieucf867442012-06-29 20:36:14 +000010445
10446 EnumConstantDecl *Last = cast<EnumConstantDecl>(Elements[NumElements - 1]),
10447 *Next = cast<EnumConstantDecl>(Elements[NumElements - 2]);
10448
10449 S.Diag(Last->getLocation(), diag::note_identical_enum_values)
10450 << FixItHint::CreateReplacement(Last->getInitExpr()->getSourceRange(),
10451 Next->getName());
Richard Trieu01cf0932012-05-30 01:01:11 +000010452}
10453
Mike Stump6814d1c2009-05-16 07:06:02 +000010454void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000010455 SourceLocation RBraceLoc, Decl *EnumDeclX,
10456 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010457 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000010458 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000010459 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010460
10461 if (Attr)
10462 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000010463
Eli Friedmand0e60972009-12-11 01:34:50 +000010464 if (Enum->isDependentType()) {
10465 for (unsigned i = 0; i != NumElements; ++i) {
10466 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000010467 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000010468 if (!ECD) continue;
10469
10470 ECD->setType(EnumType);
10471 }
10472
John McCall9aa35be2010-05-06 08:49:23 +000010473 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000010474 return;
10475 }
10476
Chris Lattner67933c02007-08-28 05:10:31 +000010477 // TODO: If the result value doesn't fit in an int, it must be a long or long
10478 // long value. ISO C does not support this, but GCC does as an extension,
10479 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000010480 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10481 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10482 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010483
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010484 // Verify that all the values are okay, compute the size of the values, and
10485 // reverse the list.
10486 unsigned NumNegativeBits = 0;
10487 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000010488
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010489 // Keep track of whether all elements have type int.
10490 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000010491
Chris Lattnerc1915e22007-01-25 07:29:02 +000010492 for (unsigned i = 0; i != NumElements; ++i) {
10493 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000010494 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000010495 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000010496
Chris Lattnerbf478cb2007-08-28 05:27:00 +000010497 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000010498
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010499 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000010500 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000010501 NumPositiveBits = std::max(NumPositiveBits,
10502 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010503 else
Chris Lattner49f980c2008-01-14 21:47:29 +000010504 NumNegativeBits = std::max(NumNegativeBits,
10505 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000010506
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010507 // Keep track of whether every enum element has type int (very commmon).
10508 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000010509 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000010510 }
Mike Stump11289f42009-09-09 15:08:12 +000010511
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010512 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010513 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010514 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010515
John McCall56774992009-12-09 09:09:27 +000010516 // C++0x N3000 [conv.prom]p3:
10517 // An rvalue of an unscoped enumeration type whose underlying
10518 // type is not fixed can be converted to an rvalue of the first
10519 // of the following types that can represent all the values of
10520 // the enumeration: int, unsigned int, long int, unsigned long
10521 // int, long long int, or unsigned long long int.
10522 // C99 6.4.4.3p2:
10523 // An identifier declared as an enumeration constant has type int.
10524 // The C99 rule is modified by a gcc extension
10525 QualType BestPromotionType;
10526
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010527 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000010528 // -fshort-enums is the equivalent to specifying the packed attribute on all
10529 // enum definitions.
10530 if (LangOpts.ShortEnums)
10531 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010532
Douglas Gregor0bf31402010-10-08 23:50:27 +000010533 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000010534 BestType = Enum->getIntegerType();
10535 if (BestType->isPromotableIntegerType())
10536 BestPromotionType = Context.getPromotedIntegerType(BestType);
10537 else
10538 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000010539 // We don't need to set BestWidth, because BestType is going to be the type
10540 // of the enumerators, but we do anyway because otherwise some compilers
10541 // warn that it might be used uninitialized.
10542 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010543 }
10544 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000010545 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010546 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010547 // If it's packed, check also if it fits a char or a short.
10548 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000010549 BestType = Context.SignedCharTy;
10550 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000010551 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010552 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000010553 BestType = Context.ShortTy;
10554 BestWidth = ShortWidth;
10555 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010556 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010557 BestWidth = IntWidth;
10558 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010559 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010560
John McCall56774992009-12-09 09:09:27 +000010561 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010562 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000010563 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010564 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000010565
Chris Lattner3a370bf2007-08-29 17:31:48 +000010566 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010567 Diag(Enum->getLocation(), diag::warn_enum_too_large);
10568 BestType = Context.LongLongTy;
10569 }
10570 }
John McCall56774992009-12-09 09:09:27 +000010571 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010572 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000010573 // If there is no negative value, figure out the smallest type that fits
10574 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010575 // If it's packed, check also if it fits a char or a short.
10576 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000010577 BestType = Context.UnsignedCharTy;
10578 BestPromotionType = Context.IntTy;
10579 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000010580 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000010581 BestType = Context.UnsignedShortTy;
10582 BestPromotionType = Context.IntTy;
10583 BestWidth = ShortWidth;
10584 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010585 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010586 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000010587 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010588 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010589 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000010590 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000010591 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010592 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000010593 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010594 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010595 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000010596 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000010597 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010598 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010599 "How could an initializer get larger than ULL?");
10600 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000010601 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000010602 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000010603 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000010604 }
10605 }
Mike Stump11289f42009-09-09 15:08:12 +000010606
Chris Lattner3a370bf2007-08-29 17:31:48 +000010607 // Loop over all of the enumerator constants, changing their types to match
10608 // the type of the enum if needed.
10609 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +000010610 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010611 if (!ECD) continue; // Already issued a diagnostic.
10612
10613 // Standard C says the enumerators have int type, but we allow, as an
10614 // extension, the enumerators to be larger than int size. If each
10615 // enumerator value fits in an int, type it as an int, otherwise type it the
10616 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
10617 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000010618
10619 // Determine whether the value fits into an int.
10620 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010621
10622 // If it fits into an integer type, force it. Otherwise force it to match
10623 // the enum decl type.
10624 QualType NewTy;
10625 unsigned NewWidth;
10626 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010627 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000010628 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000010629 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000010630 NewTy = Context.IntTy;
10631 NewWidth = IntWidth;
10632 NewSign = true;
10633 } else if (ECD->getType() == BestType) {
10634 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000010635 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000010636 // C++ [dcl.enum]p4: Following the closing brace of an
10637 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000010638 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000010639 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010640 continue;
10641 } else {
10642 NewTy = BestType;
10643 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000010644 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000010645 }
10646
10647 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010648 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010649 InitVal.setIsSigned(NewSign);
10650 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000010651
Chris Lattner3a370bf2007-08-29 17:31:48 +000010652 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000010653 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000010654 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000010655 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000010656 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000010657 ECD->getInitExpr(),
10658 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000010659 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000010660 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000010661 // C++ [dcl.enum]p4: Following the closing brace of an
10662 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000010663 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000010664 ECD->setType(EnumType);
10665 else
10666 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000010667 }
Mike Stump11289f42009-09-09 15:08:12 +000010668
John McCall9aa35be2010-05-06 08:49:23 +000010669 Enum->completeDefinition(BestType, BestPromotionType,
10670 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000010671
10672 // If we're declaring a function, ensure this decl isn't forgotten about -
10673 // it needs to go into the function scope.
10674 if (InFunctionDeclarator)
10675 DeclsInPrototypeScope.push_back(Enum);
10676
Richard Trieu01cf0932012-05-30 01:01:11 +000010677 CheckForUniqueEnumValues(*this, Elements, NumElements, Enum, EnumType);
Chris Lattnerc1915e22007-01-25 07:29:02 +000010678}
Chris Lattner1300fb92007-01-23 23:42:53 +000010679
Abramo Bagnara348823a2011-03-03 14:20:18 +000010680Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10681 SourceLocation StartLoc,
10682 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000010683 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000010684
Douglas Gregor278f52e2009-05-30 00:08:05 +000010685 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000010686 AsmString, StartLoc,
10687 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010688 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000010689 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000010690}
Eli Friedman5ed51982009-06-05 02:44:36 +000010691
Douglas Gregor22d09742012-01-03 18:04:46 +000010692DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10693 SourceLocation ImportLoc,
10694 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000010695 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000010696 Module::AllVisible,
10697 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000010698 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000010699 return true;
10700
Douglas Gregorba345522011-12-02 23:23:56 +000010701 llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10702 Module *ModCheck = Mod;
10703 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10704 // If we've run out of module parents, just drop the remaining identifiers.
10705 // We need the length to be consistent.
10706 if (!ModCheck)
10707 break;
10708 ModCheck = ModCheck->Parent;
10709
10710 IdentifierLocs.push_back(Path[I].second);
10711 }
10712
10713 ImportDecl *Import = ImportDecl::Create(Context,
10714 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000010715 AtLoc.isValid()? AtLoc : ImportLoc,
10716 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000010717 Context.getTranslationUnitDecl()->addDecl(Import);
10718 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000010719}
10720
David Chisnall0867d9c2012-02-18 16:12:34 +000010721void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10722 IdentifierInfo* AliasName,
10723 SourceLocation PragmaLoc,
10724 SourceLocation NameLoc,
10725 SourceLocation AliasNameLoc) {
10726 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10727 LookupOrdinaryName);
10728 AsmLabelAttr *Attr =
10729 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall0867d9c2012-02-18 16:12:34 +000010730
10731 if (PrevDecl)
10732 PrevDecl->addAttr(Attr);
10733 else
10734 (void)ExtnameUndeclaredIdentifiers.insert(
10735 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10736}
10737
Eli Friedman5ed51982009-06-05 02:44:36 +000010738void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10739 SourceLocation PragmaLoc,
10740 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010741 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000010742
Eli Friedman5ed51982009-06-05 02:44:36 +000010743 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010744 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +000010745 } else {
10746 (void)WeakUndeclaredIdentifiers.insert(
10747 std::pair<IdentifierInfo*,WeakInfo>
10748 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000010749 }
Eli Friedman5ed51982009-06-05 02:44:36 +000010750}
10751
10752void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10753 IdentifierInfo* AliasName,
10754 SourceLocation PragmaLoc,
10755 SourceLocation NameLoc,
10756 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000010757 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10758 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000010759 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000010760
Eli Friedman5ed51982009-06-05 02:44:36 +000010761 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000010762 if (!PrevDecl->hasAttr<AliasAttr>())
10763 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000010764 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000010765 } else {
10766 (void)WeakUndeclaredIdentifiers.insert(
10767 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000010768 }
Eli Friedman5ed51982009-06-05 02:44:36 +000010769}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000010770
10771Decl *Sema::getObjCDeclContext() const {
10772 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10773}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000010774
10775AvailabilityResult Sema::getCurContextAvailability() const {
10776 const Decl *D = cast<Decl>(getCurLexicalContext());
10777 // A category implicitly has the availability of the interface.
10778 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10779 D = CatD->getClassInterface();
10780
10781 return D->getAvailability();
10782}