blob: 10d04fa9a31277a1bcc200956b061095593ffebb [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregor752a5952011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Alexis Hunt96d5c762009-11-21 08:43:09 +0000524 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
525 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
526 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000531
John McCall3696dcb2010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539}
540
Douglas Gregor556877c2008-04-13 21:30:24 +0000541/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
542/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000546BaseResult
John McCall48871652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregorc40290e2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky19b9f952010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000561
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000573}
Douglas Gregor556877c2008-04-13 21:30:24 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575/// \brief Performs the actual work of attaching the given base class
576/// specifiers to a C++ class.
577bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
578 unsigned NumBases) {
579 if (NumBases == 0)
580 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000581
582 // Used to keep track of which base types we have already seen, so
583 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000595 if (!Class->hasObjectMember()) {
596 if (const RecordType *FDTTy =
597 NewBaseType.getTypePtr()->getAs<RecordType>())
598 if (FDTTy->getDecl()->hasObjectMember())
599 Class->setHasObjectMember(true);
600 }
601
Douglas Gregor29a92472008-10-22 17:49:05 +0000602 if (KnownBaseTypes[NewBaseType]) {
603 // C++ [class.mi]p3:
604 // A class shall not be specified as a direct base class of a
605 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
626 // Delete the remaining (good) base class specifiers, since their
627 // data has been copied into the CXXRecordDecl.
628 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000630
631 return Invalid;
632}
633
634/// ActOnBaseSpecifiers - Attach the given base specifiers to the
635/// class, after checking whether there are any duplicate base
636/// classes.
John McCall48871652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000646
John McCalle78aac42010-03-10 03:28:59 +0000647static CXXRecordDecl *GetClassForType(QualType T) {
648 if (const RecordType *RT = T->getAs<RecordType>())
649 return cast<CXXRecordDecl>(RT->getDecl());
650 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
651 return ICT->getDecl();
652 else
653 return 0;
654}
655
Douglas Gregor36d1b142009-10-06 17:59:45 +0000656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
John McCalle78aac42010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
John McCalle78aac42010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCall67da35c2010-02-04 22:26:26 +0000670 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
671 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672}
673
674/// \brief Determine whether the type \p Derived is a C++ class that is
675/// derived from the type \p Base.
676bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
677 if (!getLangOptions().CPlusPlus)
678 return false;
679
John McCalle78aac42010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlssona70cff62010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000693 assert(BasePathArray.empty() && "Base path array must be empty!");
694 assert(Paths.isRecordingPaths() && "Must record paths!");
695
696 const CXXBasePath &Path = Paths.front();
697
698 // We first go backward and check if we have a virtual base.
699 // FIXME: It would be better if CXXBasePath had the base specifier for
700 // the nearest virtual base.
701 unsigned Start = 0;
702 for (unsigned I = Path.size(); I != 0; --I) {
703 if (Path[I - 1].Base->isVirtual()) {
704 Start = I - 1;
705 break;
706 }
707 }
708
709 // Now add all bases.
710 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000712}
713
Douglas Gregor88d292c2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallcf142162010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregor36d1b142009-10-06 17:59:45 +0000726/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
727/// conversion (where Derived and Base are class types) is
728/// well-formed, meaning that the conversion is unambiguous (and
729/// that all of the base classes are accessible). Returns true
730/// and emits a diagnostic if the code is ill-formed, returns false
731/// otherwise. Loc is the location where this routine should point to
732/// if there is an error, and Range is the source range to highlight
733/// if there is an error.
734bool
735Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 // First, determine whether the path from Derived to Base is
742 // ambiguous. This is slightly more expensive than checking whether
743 // the Derived to Base conversion exists, because here we need to
744 // explore multiple paths to determine if there is an ambiguity.
745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
746 /*DetectVirtual=*/false);
747 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(DerivationOkay &&
749 "Can only be used with a derived-to-base conversion");
750 (void)DerivationOkay;
751
752 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000753 if (InaccessibleBaseID) {
754 // Check that the base class can be accessed.
755 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
756 InaccessibleBaseID)) {
757 case AR_inaccessible:
758 return true;
759 case AR_accessible:
760 case AR_dependent:
761 case AR_delayed:
762 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000763 }
John McCall5b0829a2010-02-10 09:31:12 +0000764 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000770 }
771
772 // We know that the derived-to-base conversion is ambiguous, and
773 // we're going to produce a diagnostic. Perform the derived-to-base
774 // search just one more time to compute all of the possible paths so
775 // that we can print them out. This is more expensive than any of
776 // the previous derived-to-base checks we've done, but at this point
777 // performance isn't as much of an issue.
778 Paths.clear();
779 Paths.setRecordingPaths(true);
780 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(StillOkay && "Can only be used with a derived-to-base conversion");
782 (void)StillOkay;
783
784 // Build up a textual representation of the ambiguous paths, e.g.,
785 // D -> B -> A, that will be used to illustrate the ambiguous
786 // conversions in the diagnostic. We only print one of the paths
787 // to each base class subobject.
788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
789
790 Diag(Loc, AmbigiousBaseConvID)
791 << Derived << Base << PathDisplayStr << Range << Name;
792 return true;
793}
794
795bool
796Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806}
807
808
809/// @brief Builds a string representing ambiguous paths from a
810/// specific derived class to different subobjects of the same base
811/// class.
812///
813/// This function builds a string that can be used in error messages
814/// to show the different paths that one can take through the
815/// inheritance hierarchy to go from the derived class to different
816/// subobjects of a base class. The result looks something like this:
817/// @code
818/// struct D -> struct B -> struct A
819/// struct D -> struct C -> struct A
820/// @endcode
821std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
822 std::string PathDisplayStr;
823 std::set<unsigned> DisplayedPaths;
824 for (CXXBasePaths::paths_iterator Path = Paths.begin();
825 Path != Paths.end(); ++Path) {
826 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
827 // We haven't displayed a path to this particular base
828 // class subobject yet.
829 PathDisplayStr += "\n ";
830 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
831 for (CXXBasePath::const_iterator Element = Path->begin();
832 Element != Path->end(); ++Element)
833 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
834 }
835 }
836
837 return PathDisplayStr;
838}
839
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnarad7340582010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853}
854
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000855/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
856/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
857/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000858/// any.
John McCall48871652010-08-21 09:40:31 +0000859Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000862 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
863 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000864 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000865 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
866 DeclarationName Name = NameInfo.getName();
867 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000868
869 // For anonymous bitfields, the location should point to the type.
870 if (Loc.isInvalid())
871 Loc = D.getSourceRange().getBegin();
872
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000873 Expr *BitWidth = static_cast<Expr*>(BW);
874 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000875
John McCallb1cd7da2010-06-04 08:34:12 +0000876 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000877 assert(!DS.isFriendSpecified());
878
John McCallb1cd7da2010-06-04 08:34:12 +0000879 bool isFunc = false;
880 if (D.isFunctionDeclarator())
881 isFunc = true;
882 else if (D.getNumTypeObjects() == 0 &&
883 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000884 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000885 isFunc = TDType->isFunctionType();
886 }
887
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000888 // C++ 9.2p6: A member shall not be declared to have automatic storage
889 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000890 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
891 // data members and cannot be applied to names declared const or static,
892 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893 switch (DS.getStorageClassSpec()) {
894 case DeclSpec::SCS_unspecified:
895 case DeclSpec::SCS_typedef:
896 case DeclSpec::SCS_static:
897 // FALL THROUGH.
898 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000899 case DeclSpec::SCS_mutable:
900 if (isFunc) {
901 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000902 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000903 else
Chris Lattner3b054132008-11-19 05:08:23 +0000904 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Sebastian Redl8071edb2008-11-17 23:24:37 +0000906 // FIXME: It would be nicer if the keyword was ignored only for this
907 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000908 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000909 }
910 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000911 default:
912 if (DS.getStorageClassSpecLoc().isValid())
913 Diag(DS.getStorageClassSpecLoc(),
914 diag::err_storageclass_invalid_for_member);
915 else
916 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
917 D.getMutableDeclSpec().ClearStorageClassSpecs();
918 }
919
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000920 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
921 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000922 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000923
924 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000925 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000926 CXXScopeSpec &SS = D.getCXXScopeSpec();
927
928
929 if (SS.isSet() && !SS.isInvalid()) {
930 // The user provided a superfluous scope specifier inside a class
931 // definition:
932 //
933 // class X {
934 // int X::member;
935 // };
936 DeclContext *DC = 0;
937 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
938 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
939 << Name << FixItHint::CreateRemoval(SS.getRange());
940 else
941 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
942 << Name << SS.getRange();
943
944 SS.clear();
945 }
946
Douglas Gregor3447e762009-08-20 22:52:58 +0000947 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000948 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000949 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
950 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000951 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000952 } else {
John McCall48871652010-08-21 09:40:31 +0000953 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000954 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000955 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000956 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000957
958 // Non-instance-fields can't have a bitfield.
959 if (BitWidth) {
960 if (Member->isInvalidDecl()) {
961 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000962 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000963 // C++ 9.6p3: A bit-field shall not be a static member.
964 // "static member 'A' cannot be a bit-field"
965 Diag(Loc, diag::err_static_not_bitfield)
966 << Name << BitWidth->getSourceRange();
967 } else if (isa<TypedefDecl>(Member)) {
968 // "typedef member 'x' cannot be a bit-field"
969 Diag(Loc, diag::err_typedef_not_bitfield)
970 << Name << BitWidth->getSourceRange();
971 } else {
972 // A function typedef ("typedef int f(); f a;").
973 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
974 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000975 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000976 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerd26760a2009-03-05 23:01:03 +0000979 BitWidth = 0;
980 Member->setInvalidDecl();
981 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000982
983 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor3447e762009-08-20 22:52:58 +0000985 // If we have declared a member function template, set the access of the
986 // templated declaration as well.
987 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
988 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000989 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000990
Douglas Gregor92751d42008-11-17 22:58:34 +0000991 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000992
Douglas Gregor0c880302009-03-11 23:00:04 +0000993 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000994 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000995 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000996 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000999 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001000 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001001 }
John McCall48871652010-08-21 09:40:31 +00001002 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001003}
1004
Douglas Gregor15e77a22009-12-31 09:10:24 +00001005/// \brief Find the direct and/or virtual base specifiers that
1006/// correspond to the given base type, for use in base initialization
1007/// within a constructor.
1008static bool FindBaseInitializer(Sema &SemaRef,
1009 CXXRecordDecl *ClassDecl,
1010 QualType BaseType,
1011 const CXXBaseSpecifier *&DirectBaseSpec,
1012 const CXXBaseSpecifier *&VirtualBaseSpec) {
1013 // First, check for a direct base class.
1014 DirectBaseSpec = 0;
1015 for (CXXRecordDecl::base_class_const_iterator Base
1016 = ClassDecl->bases_begin();
1017 Base != ClassDecl->bases_end(); ++Base) {
1018 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1019 // We found a direct base of this type. That's what we're
1020 // initializing.
1021 DirectBaseSpec = &*Base;
1022 break;
1023 }
1024 }
1025
1026 // Check for a virtual base class.
1027 // FIXME: We might be able to short-circuit this if we know in advance that
1028 // there are no virtual bases.
1029 VirtualBaseSpec = 0;
1030 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1031 // We haven't found a base yet; search the class hierarchy for a
1032 // virtual base class.
1033 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1034 /*DetectVirtual=*/false);
1035 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1036 BaseType, Paths)) {
1037 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1038 Path != Paths.end(); ++Path) {
1039 if (Path->back().Base->isVirtual()) {
1040 VirtualBaseSpec = Path->back().Base;
1041 break;
1042 }
1043 }
1044 }
1045 }
1046
1047 return DirectBaseSpec || VirtualBaseSpec;
1048}
1049
Douglas Gregore8381c02008-11-05 04:29:56 +00001050/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001051MemInitResult
John McCall48871652010-08-21 09:40:31 +00001052Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001053 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001054 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001055 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001056 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001057 SourceLocation IdLoc,
1058 SourceLocation LParenLoc,
1059 ExprTy **Args, unsigned NumArgs,
Douglas Gregore8381c02008-11-05 04:29:56 +00001060 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001061 if (!ConstructorD)
1062 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001063
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001064 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001065
1066 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001067 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001068 if (!Constructor) {
1069 // The user wrote a constructor initializer on a function that is
1070 // not a C++ constructor. Ignore the error for now, because we may
1071 // have more member initializers coming; we'll diagnose it just
1072 // once in ActOnMemInitializers.
1073 return true;
1074 }
1075
1076 CXXRecordDecl *ClassDecl = Constructor->getParent();
1077
1078 // C++ [class.base.init]p2:
1079 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001080 // constructor's class and, if not found in that scope, are looked
1081 // up in the scope containing the constructor's definition.
1082 // [Note: if the constructor's class contains a member with the
1083 // same name as a direct or virtual base class of the class, a
1084 // mem-initializer-id naming the member or base class and composed
1085 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001086 // mem-initializer-id for the hidden base class may be specified
1087 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001088 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001089 // Look for a member, first.
1090 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001091 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001092 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001093 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001094 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001095
Francois Pichetd583da02010-12-04 09:14:42 +00001096 if (Member)
1097 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001098 LParenLoc, RParenLoc);
Francois Pichetd583da02010-12-04 09:14:42 +00001099 // Handle anonymous union case.
1100 if (IndirectFieldDecl* IndirectField
1101 = dyn_cast<IndirectFieldDecl>(*Result.first))
1102 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1103 NumArgs, IdLoc,
1104 LParenLoc, RParenLoc);
1105 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001106 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001107 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001108 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001109 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001110
1111 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001112 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001113 } else {
1114 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1115 LookupParsedName(R, S, &SS);
1116
1117 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1118 if (!TyD) {
1119 if (R.isAmbiguous()) return true;
1120
John McCallda6841b2010-04-09 19:01:14 +00001121 // We don't want access-control diagnostics here.
1122 R.suppressDiagnostics();
1123
Douglas Gregora3b624a2010-01-19 06:46:48 +00001124 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1125 bool NotUnknownSpecialization = false;
1126 DeclContext *DC = computeDeclContext(SS, false);
1127 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1128 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1129
1130 if (!NotUnknownSpecialization) {
1131 // When the scope specifier can refer to a member of an unknown
1132 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001133 BaseType = CheckTypenameType(ETK_None,
1134 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001135 *MemberOrBase, SourceLocation(),
1136 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001137 if (BaseType.isNull())
1138 return true;
1139
Douglas Gregora3b624a2010-01-19 06:46:48 +00001140 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001141 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001142 }
1143 }
1144
Douglas Gregor15e77a22009-12-31 09:10:24 +00001145 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001146 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001147 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1148 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001149 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001150 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001151 // We have found a non-static data member with a similar
1152 // name to what was typed; complain and initialize that
1153 // member.
1154 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1155 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001156 << FixItHint::CreateReplacement(R.getNameLoc(),
1157 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001158 Diag(Member->getLocation(), diag::note_previous_decl)
1159 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001160
1161 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1162 LParenLoc, RParenLoc);
1163 }
1164 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1165 const CXXBaseSpecifier *DirectBaseSpec;
1166 const CXXBaseSpecifier *VirtualBaseSpec;
1167 if (FindBaseInitializer(*this, ClassDecl,
1168 Context.getTypeDeclType(Type),
1169 DirectBaseSpec, VirtualBaseSpec)) {
1170 // We have found a direct or virtual base class with a
1171 // similar name to what was typed; complain and initialize
1172 // that base class.
1173 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1174 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001175 << FixItHint::CreateReplacement(R.getNameLoc(),
1176 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001177
1178 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1179 : VirtualBaseSpec;
1180 Diag(BaseSpec->getSourceRange().getBegin(),
1181 diag::note_base_class_specified_here)
1182 << BaseSpec->getType()
1183 << BaseSpec->getSourceRange();
1184
Douglas Gregor15e77a22009-12-31 09:10:24 +00001185 TyD = Type;
1186 }
1187 }
1188 }
1189
Douglas Gregora3b624a2010-01-19 06:46:48 +00001190 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001191 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1192 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1193 return true;
1194 }
John McCallb5a0d312009-12-21 10:41:20 +00001195 }
1196
Douglas Gregora3b624a2010-01-19 06:46:48 +00001197 if (BaseType.isNull()) {
1198 BaseType = Context.getTypeDeclType(TyD);
1199 if (SS.isSet()) {
1200 NestedNameSpecifier *Qualifier =
1201 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001202
Douglas Gregora3b624a2010-01-19 06:46:48 +00001203 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001204 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001205 }
John McCallb5a0d312009-12-21 10:41:20 +00001206 }
1207 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
John McCallbcd03502009-12-07 02:54:59 +00001209 if (!TInfo)
1210 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001211
John McCallbcd03502009-12-07 02:54:59 +00001212 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001213 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001214}
1215
John McCalle22a04a2009-11-04 23:02:40 +00001216/// Checks an initializer expression for use of uninitialized fields, such as
1217/// containing the field that is being initialized. Returns true if there is an
1218/// uninitialized field was used an updates the SourceLocation parameter; false
1219/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001220static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001221 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001222 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001223 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1224
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001225 if (isa<CallExpr>(S)) {
1226 // Do not descend into function calls or constructors, as the use
1227 // of an uninitialized field may be valid. One would have to inspect
1228 // the contents of the function/ctor to determine if it is safe or not.
1229 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1230 // may be safe, depending on what the function/ctor does.
1231 return false;
1232 }
1233 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1234 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001235
1236 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1237 // The member expression points to a static data member.
1238 assert(VD->isStaticDataMember() &&
1239 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001240 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001241 return false;
1242 }
1243
1244 if (isa<EnumConstantDecl>(RhsField)) {
1245 // The member expression points to an enum.
1246 return false;
1247 }
1248
John McCalle22a04a2009-11-04 23:02:40 +00001249 if (RhsField == LhsField) {
1250 // Initializing a field with itself. Throw a warning.
1251 // But wait; there are exceptions!
1252 // Exception #1: The field may not belong to this record.
1253 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001254 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001255 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1256 // Even though the field matches, it does not belong to this record.
1257 return false;
1258 }
1259 // None of the exceptions triggered; return true to indicate an
1260 // uninitialized field was used.
1261 *L = ME->getMemberLoc();
1262 return true;
1263 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001264 } else if (isa<SizeOfAlignOfExpr>(S)) {
1265 // sizeof/alignof doesn't reference contents, do not warn.
1266 return false;
1267 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1268 // address-of doesn't reference contents (the pointer may be dereferenced
1269 // in the same expression but it would be rare; and weird).
1270 if (UOE->getOpcode() == UO_AddrOf)
1271 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001272 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001273 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1274 it != e; ++it) {
1275 if (!*it) {
1276 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001277 continue;
1278 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001279 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1280 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001281 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001282 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001283}
1284
John McCallfaf5fb42010-08-26 23:41:50 +00001285MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001286Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001287 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001288 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001289 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001290 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1291 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1292 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001293 "Member must be a FieldDecl or IndirectFieldDecl");
1294
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001295 if (Member->isInvalidDecl())
1296 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001297
John McCalle22a04a2009-11-04 23:02:40 +00001298 // Diagnose value-uses of fields to initialize themselves, e.g.
1299 // foo(foo)
1300 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001301 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001302 for (unsigned i = 0; i < NumArgs; ++i) {
1303 SourceLocation L;
1304 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1305 // FIXME: Return true in the case when other fields are used before being
1306 // uninitialized. For example, let this field be the i'th field. When
1307 // initializing the i'th field, throw a warning if any of the >= i'th
1308 // fields are used, as they are not yet initialized.
1309 // Right now we are only handling the case where the i'th field uses
1310 // itself in its initializer.
1311 Diag(L, diag::warn_field_is_uninit);
1312 }
1313 }
1314
Eli Friedman8e1433b2009-07-29 19:44:27 +00001315 bool HasDependentArg = false;
1316 for (unsigned i = 0; i < NumArgs; i++)
1317 HasDependentArg |= Args[i]->isTypeDependent();
1318
Chandler Carruthd44c3102010-12-06 09:23:57 +00001319 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001320 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001321 // Can't check initialization for a member of dependent type or when
1322 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001323 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1324 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001325
1326 // Erase any temporaries within this evaluation context; we're not
1327 // going to track them in the AST, since we'll be rebuilding the
1328 // ASTs during template instantiation.
1329 ExprTemporaries.erase(
1330 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1331 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001332 } else {
1333 // Initialize the member.
1334 InitializedEntity MemberEntity =
1335 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1336 : InitializedEntity::InitializeMember(IndirectMember, 0);
1337 InitializationKind Kind =
1338 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001339
Chandler Carruthd44c3102010-12-06 09:23:57 +00001340 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1341
1342 ExprResult MemberInit =
1343 InitSeq.Perform(*this, MemberEntity, Kind,
1344 MultiExprArg(*this, Args, NumArgs), 0);
1345 if (MemberInit.isInvalid())
1346 return true;
1347
1348 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1349
1350 // C++0x [class.base.init]p7:
1351 // The initialization of each base and member constitutes a
1352 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001353 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001354 if (MemberInit.isInvalid())
1355 return true;
1356
1357 // If we are in a dependent context, template instantiation will
1358 // perform this type-checking again. Just save the arguments that we
1359 // received in a ParenListExpr.
1360 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1361 // of the information that we have about the member
1362 // initializer. However, deconstructing the ASTs is a dicey process,
1363 // and this approach is far more likely to get the corner cases right.
1364 if (CurContext->isDependentContext())
1365 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1366 RParenLoc);
1367 else
1368 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001369 }
1370
Chandler Carruthd44c3102010-12-06 09:23:57 +00001371 if (DirectMember) {
1372 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember,
1373 IdLoc, LParenLoc, Init,
1374 RParenLoc);
1375 } else {
1376 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember,
1377 IdLoc, LParenLoc, Init,
1378 RParenLoc);
1379 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001380}
1381
John McCallfaf5fb42010-08-26 23:41:50 +00001382MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001383Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001384 Expr **Args, unsigned NumArgs,
1385 SourceLocation LParenLoc, SourceLocation RParenLoc,
1386 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001387 bool HasDependentArg = false;
1388 for (unsigned i = 0; i < NumArgs; i++)
1389 HasDependentArg |= Args[i]->isTypeDependent();
1390
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001391 SourceLocation BaseLoc
1392 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1393
1394 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1395 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1396 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1397
1398 // C++ [class.base.init]p2:
1399 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001400 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001401 // of that class, the mem-initializer is ill-formed. A
1402 // mem-initializer-list can initialize a base class using any
1403 // name that denotes that base class type.
1404 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1405
1406 // Check for direct and virtual base classes.
1407 const CXXBaseSpecifier *DirectBaseSpec = 0;
1408 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1409 if (!Dependent) {
1410 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1411 VirtualBaseSpec);
1412
1413 // C++ [base.class.init]p2:
1414 // Unless the mem-initializer-id names a nonstatic data member of the
1415 // constructor's class or a direct or virtual base of that class, the
1416 // mem-initializer is ill-formed.
1417 if (!DirectBaseSpec && !VirtualBaseSpec) {
1418 // If the class has any dependent bases, then it's possible that
1419 // one of those types will resolve to the same type as
1420 // BaseType. Therefore, just treat this as a dependent base
1421 // class initialization. FIXME: Should we try to check the
1422 // initialization anyway? It seems odd.
1423 if (ClassDecl->hasAnyDependentBases())
1424 Dependent = true;
1425 else
1426 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1427 << BaseType << Context.getTypeDeclType(ClassDecl)
1428 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1429 }
1430 }
1431
1432 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001433 // Can't check initialization for a base of dependent type or when
1434 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001435 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001436 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1437 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001438
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001439 // Erase any temporaries within this evaluation context; we're not
1440 // going to track them in the AST, since we'll be rebuilding the
1441 // ASTs during template instantiation.
1442 ExprTemporaries.erase(
1443 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1444 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001445
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001446 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001447 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001448 LParenLoc,
1449 BaseInit.takeAs<Expr>(),
1450 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001451 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001452
1453 // C++ [base.class.init]p2:
1454 // If a mem-initializer-id is ambiguous because it designates both
1455 // a direct non-virtual base class and an inherited virtual base
1456 // class, the mem-initializer is ill-formed.
1457 if (DirectBaseSpec && VirtualBaseSpec)
1458 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001459 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001460
1461 CXXBaseSpecifier *BaseSpec
1462 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1463 if (!BaseSpec)
1464 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1465
1466 // Initialize the base.
1467 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001468 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001469 InitializationKind Kind =
1470 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1471
1472 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1473
John McCalldadc5752010-08-24 06:29:42 +00001474 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001475 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001476 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001477 if (BaseInit.isInvalid())
1478 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001479
1480 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001481
1482 // C++0x [class.base.init]p7:
1483 // The initialization of each base and member constitutes a
1484 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001485 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001486 if (BaseInit.isInvalid())
1487 return true;
1488
1489 // If we are in a dependent context, template instantiation will
1490 // perform this type-checking again. Just save the arguments that we
1491 // received in a ParenListExpr.
1492 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1493 // of the information that we have about the base
1494 // initializer. However, deconstructing the ASTs is a dicey process,
1495 // and this approach is far more likely to get the corner cases right.
1496 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001497 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001498 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1499 RParenLoc));
1500 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001501 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001502 LParenLoc,
1503 Init.takeAs<Expr>(),
1504 RParenLoc);
1505 }
1506
1507 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001508 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001509 LParenLoc,
1510 BaseInit.takeAs<Expr>(),
1511 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001512}
1513
Anders Carlsson1b00e242010-04-23 03:10:23 +00001514/// ImplicitInitializerKind - How an implicit base or member initializer should
1515/// initialize its base or member.
1516enum ImplicitInitializerKind {
1517 IIK_Default,
1518 IIK_Copy,
1519 IIK_Move
1520};
1521
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001522static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001523BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001524 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001525 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001526 bool IsInheritedVirtualBase,
1527 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001528 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001529 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1530 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001531
John McCalldadc5752010-08-24 06:29:42 +00001532 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001533
1534 switch (ImplicitInitKind) {
1535 case IIK_Default: {
1536 InitializationKind InitKind
1537 = InitializationKind::CreateDefault(Constructor->getLocation());
1538 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1539 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001540 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001541 break;
1542 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001543
Anders Carlsson1b00e242010-04-23 03:10:23 +00001544 case IIK_Copy: {
1545 ParmVarDecl *Param = Constructor->getParamDecl(0);
1546 QualType ParamType = Param->getType().getNonReferenceType();
1547
1548 Expr *CopyCtorArg =
1549 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001550 Constructor->getLocation(), ParamType,
1551 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001552
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001553 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001554 QualType ArgTy =
1555 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1556 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001557
1558 CXXCastPath BasePath;
1559 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001560 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001561 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001562 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001563
Anders Carlsson1b00e242010-04-23 03:10:23 +00001564 InitializationKind InitKind
1565 = InitializationKind::CreateDirect(Constructor->getLocation(),
1566 SourceLocation(), SourceLocation());
1567 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1568 &CopyCtorArg, 1);
1569 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001570 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001571 break;
1572 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001573
Anders Carlsson1b00e242010-04-23 03:10:23 +00001574 case IIK_Move:
1575 assert(false && "Unhandled initializer kind!");
1576 }
John McCallb268a282010-08-23 23:25:46 +00001577
Douglas Gregora40433a2010-12-07 00:41:46 +00001578 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001579 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001580 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001581
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001582 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001583 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1584 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1585 SourceLocation()),
1586 BaseSpec->isVirtual(),
1587 SourceLocation(),
1588 BaseInit.takeAs<Expr>(),
1589 SourceLocation());
1590
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001591 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001592}
1593
Anders Carlsson3c1db572010-04-23 02:15:47 +00001594static bool
1595BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001596 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001597 FieldDecl *Field,
1598 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001599 if (Field->isInvalidDecl())
1600 return true;
1601
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001602 SourceLocation Loc = Constructor->getLocation();
1603
Anders Carlsson423f5d82010-04-23 16:04:08 +00001604 if (ImplicitInitKind == IIK_Copy) {
1605 ParmVarDecl *Param = Constructor->getParamDecl(0);
1606 QualType ParamType = Param->getType().getNonReferenceType();
1607
1608 Expr *MemberExprBase =
1609 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001610 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001611
1612 // Build a reference to this field within the parameter.
1613 CXXScopeSpec SS;
1614 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1615 Sema::LookupMemberName);
1616 MemberLookup.addDecl(Field, AS_public);
1617 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001618 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001619 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001620 ParamType, Loc,
1621 /*IsArrow=*/false,
1622 SS,
1623 /*FirstQualifierInScope=*/0,
1624 MemberLookup,
1625 /*TemplateArgs=*/0);
1626 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001627 return true;
1628
Douglas Gregor94f9a482010-05-05 05:51:00 +00001629 // When the field we are copying is an array, create index variables for
1630 // each dimension of the array. We use these index variables to subscript
1631 // the source array, and other clients (e.g., CodeGen) will perform the
1632 // necessary iteration with these index variables.
1633 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1634 QualType BaseType = Field->getType();
1635 QualType SizeType = SemaRef.Context.getSizeType();
1636 while (const ConstantArrayType *Array
1637 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1638 // Create the iteration variable for this array index.
1639 IdentifierInfo *IterationVarName = 0;
1640 {
1641 llvm::SmallString<8> Str;
1642 llvm::raw_svector_ostream OS(Str);
1643 OS << "__i" << IndexVariables.size();
1644 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1645 }
1646 VarDecl *IterationVar
1647 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1648 IterationVarName, SizeType,
1649 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001650 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001651 IndexVariables.push_back(IterationVar);
1652
1653 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001654 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001655 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001656 assert(!IterationVarRef.isInvalid() &&
1657 "Reference to invented variable cannot fail!");
1658
1659 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001660 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001661 Loc,
John McCallb268a282010-08-23 23:25:46 +00001662 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001663 Loc);
1664 if (CopyCtorArg.isInvalid())
1665 return true;
1666
1667 BaseType = Array->getElementType();
1668 }
1669
1670 // Construct the entity that we will be initializing. For an array, this
1671 // will be first element in the array, which may require several levels
1672 // of array-subscript entities.
1673 llvm::SmallVector<InitializedEntity, 4> Entities;
1674 Entities.reserve(1 + IndexVariables.size());
1675 Entities.push_back(InitializedEntity::InitializeMember(Field));
1676 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1677 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1678 0,
1679 Entities.back()));
1680
1681 // Direct-initialize to use the copy constructor.
1682 InitializationKind InitKind =
1683 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1684
1685 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1686 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1687 &CopyCtorArgE, 1);
1688
John McCalldadc5752010-08-24 06:29:42 +00001689 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001690 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001691 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001692 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001693 if (MemberInit.isInvalid())
1694 return true;
1695
1696 CXXMemberInit
1697 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1698 MemberInit.takeAs<Expr>(), Loc,
1699 IndexVariables.data(),
1700 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001701 return false;
1702 }
1703
Anders Carlsson423f5d82010-04-23 16:04:08 +00001704 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1705
Anders Carlsson3c1db572010-04-23 02:15:47 +00001706 QualType FieldBaseElementType =
1707 SemaRef.Context.getBaseElementType(Field->getType());
1708
Anders Carlsson3c1db572010-04-23 02:15:47 +00001709 if (FieldBaseElementType->isRecordType()) {
1710 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001711 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001712 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001713
1714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001715 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001716 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001717
Douglas Gregora40433a2010-12-07 00:41:46 +00001718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001719 if (MemberInit.isInvalid())
1720 return true;
1721
1722 CXXMemberInit =
1723 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001724 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001725 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001726 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001727 return false;
1728 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001729
1730 if (FieldBaseElementType->isReferenceType()) {
1731 SemaRef.Diag(Constructor->getLocation(),
1732 diag::err_uninitialized_member_in_ctor)
1733 << (int)Constructor->isImplicit()
1734 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1735 << 0 << Field->getDeclName();
1736 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1737 return true;
1738 }
1739
1740 if (FieldBaseElementType.isConstQualified()) {
1741 SemaRef.Diag(Constructor->getLocation(),
1742 diag::err_uninitialized_member_in_ctor)
1743 << (int)Constructor->isImplicit()
1744 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1745 << 1 << Field->getDeclName();
1746 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1747 return true;
1748 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001749
1750 // Nothing to initialize.
1751 CXXMemberInit = 0;
1752 return false;
1753}
John McCallbc83b3f2010-05-20 23:23:51 +00001754
1755namespace {
1756struct BaseAndFieldInfo {
1757 Sema &S;
1758 CXXConstructorDecl *Ctor;
1759 bool AnyErrorsInInits;
1760 ImplicitInitializerKind IIK;
1761 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1762 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1763
1764 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1765 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1766 // FIXME: Handle implicit move constructors.
1767 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1768 IIK = IIK_Copy;
1769 else
1770 IIK = IIK_Default;
1771 }
1772};
1773}
1774
1775static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1776 FieldDecl *Top, FieldDecl *Field) {
1777
Chandler Carruth139e9622010-06-30 02:59:29 +00001778 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001779 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001780 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001781 return false;
1782 }
1783
1784 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1785 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1786 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001787 CXXRecordDecl *FieldClassDecl
1788 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001789
1790 // Even though union members never have non-trivial default
1791 // constructions in C++03, we still build member initializers for aggregate
1792 // record types which can be union members, and C++0x allows non-trivial
1793 // default constructors for union members, so we ensure that only one
1794 // member is initialized for these.
1795 if (FieldClassDecl->isUnion()) {
1796 // First check for an explicit initializer for one field.
1797 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1798 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1799 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001800 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001801
1802 // Once we've initialized a field of an anonymous union, the union
1803 // field in the class is also initialized, so exit immediately.
1804 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001805 } else if ((*FA)->isAnonymousStructOrUnion()) {
1806 if (CollectFieldInitializer(Info, Top, *FA))
1807 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001808 }
1809 }
1810
1811 // Fallthrough and construct a default initializer for the union as
1812 // a whole, which can call its default constructor if such a thing exists
1813 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1814 // behavior going forward with C++0x, when anonymous unions there are
1815 // finalized, we should revisit this.
1816 } else {
1817 // For structs, we simply descend through to initialize all members where
1818 // necessary.
1819 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1820 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1821 if (CollectFieldInitializer(Info, Top, *FA))
1822 return true;
1823 }
1824 }
John McCallbc83b3f2010-05-20 23:23:51 +00001825 }
1826
1827 // Don't try to build an implicit initializer if there were semantic
1828 // errors in any of the initializers (and therefore we might be
1829 // missing some that the user actually wrote).
1830 if (Info.AnyErrorsInInits)
1831 return false;
1832
1833 CXXBaseOrMemberInitializer *Init = 0;
1834 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1835 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001836
Francois Pichetd583da02010-12-04 09:14:42 +00001837 if (Init)
1838 Info.AllToInit.push_back(Init);
1839
John McCallbc83b3f2010-05-20 23:23:51 +00001840 return false;
1841}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001842
Eli Friedman9cf6b592009-11-09 19:20:36 +00001843bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001844Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001845 CXXBaseOrMemberInitializer **Initializers,
1846 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001847 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001848 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001849 // Just store the initializers as written, they will be checked during
1850 // instantiation.
1851 if (NumInitializers > 0) {
1852 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1853 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1854 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1855 memcpy(baseOrMemberInitializers, Initializers,
1856 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1857 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1858 }
1859
1860 return false;
1861 }
1862
John McCallbc83b3f2010-05-20 23:23:51 +00001863 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001864
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001865 // We need to build the initializer AST according to order of construction
1866 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001867 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001868 if (!ClassDecl)
1869 return true;
1870
Eli Friedman9cf6b592009-11-09 19:20:36 +00001871 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001872
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001873 for (unsigned i = 0; i < NumInitializers; i++) {
1874 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001875
1876 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001877 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001878 else
Francois Pichetd583da02010-12-04 09:14:42 +00001879 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001880 }
1881
Anders Carlsson43c64af2010-04-21 19:52:01 +00001882 // Keep track of the direct virtual bases.
1883 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1884 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1885 E = ClassDecl->bases_end(); I != E; ++I) {
1886 if (I->isVirtual())
1887 DirectVBases.insert(I);
1888 }
1889
Anders Carlssondb0a9652010-04-02 06:26:44 +00001890 // Push virtual bases before others.
1891 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1892 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1893
1894 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001895 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1896 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001897 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001898 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001899 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001900 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001901 VBase, IsInheritedVirtualBase,
1902 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001903 HadError = true;
1904 continue;
1905 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001906
John McCallbc83b3f2010-05-20 23:23:51 +00001907 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001908 }
1909 }
Mike Stump11289f42009-09-09 15:08:12 +00001910
John McCallbc83b3f2010-05-20 23:23:51 +00001911 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001912 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1913 E = ClassDecl->bases_end(); Base != E; ++Base) {
1914 // Virtuals are in the virtual base list and already constructed.
1915 if (Base->isVirtual())
1916 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001917
Anders Carlssondb0a9652010-04-02 06:26:44 +00001918 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001919 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1920 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001921 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001922 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001923 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001924 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001925 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001926 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001927 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001928 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001929
John McCallbc83b3f2010-05-20 23:23:51 +00001930 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001931 }
1932 }
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCallbc83b3f2010-05-20 23:23:51 +00001934 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001935 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001936 E = ClassDecl->field_end(); Field != E; ++Field) {
1937 if ((*Field)->getType()->isIncompleteArrayType()) {
1938 assert(ClassDecl->hasFlexibleArrayMember() &&
1939 "Incomplete array type is not valid");
1940 continue;
1941 }
John McCallbc83b3f2010-05-20 23:23:51 +00001942 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001943 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
John McCallbc83b3f2010-05-20 23:23:51 +00001946 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001947 if (NumInitializers > 0) {
1948 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1949 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1950 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001951 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001952 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001953 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001954
John McCalla6309952010-03-16 21:39:52 +00001955 // Constructors implicitly reference the base and member
1956 // destructors.
1957 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1958 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001959 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001960
1961 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001962}
1963
Eli Friedman952c15d2009-07-21 19:28:10 +00001964static void *GetKeyForTopLevelField(FieldDecl *Field) {
1965 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001966 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001967 if (RT->getDecl()->isAnonymousStructOrUnion())
1968 return static_cast<void *>(RT->getDecl());
1969 }
1970 return static_cast<void *>(Field);
1971}
1972
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001973static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1974 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001975}
1976
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001977static void *GetKeyForMember(ASTContext &Context,
Francois Pichetd583da02010-12-04 09:14:42 +00001978 CXXBaseOrMemberInitializer *Member) {
1979 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001980 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001981
Eli Friedman952c15d2009-07-21 19:28:10 +00001982 // For fields injected into the class via declaration of an anonymous union,
1983 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00001984 FieldDecl *Field = Member->getAnyMember();
1985
John McCall23eebd92010-04-10 09:28:51 +00001986 // If the field is a member of an anonymous struct or union, our key
1987 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001988 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001989 if (RD->isAnonymousStructOrUnion()) {
1990 while (true) {
1991 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1992 if (Parent->isAnonymousStructOrUnion())
1993 RD = Parent;
1994 else
1995 break;
1996 }
1997
Anders Carlsson83ac3122010-03-30 16:19:37 +00001998 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Anders Carlssona942dcd2010-03-30 15:39:27 +00002001 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002002}
2003
Anders Carlssone857b292010-04-02 03:37:03 +00002004static void
2005DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002006 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00002007 CXXBaseOrMemberInitializer **Inits,
2008 unsigned NumInits) {
2009 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002010 return;
Mike Stump11289f42009-09-09 15:08:12 +00002011
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002012 // Don't check initializers order unless the warning is enabled at the
2013 // location of at least one initializer.
2014 bool ShouldCheckOrder = false;
2015 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2016 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2017 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2018 Init->getSourceLocation())
2019 != Diagnostic::Ignored) {
2020 ShouldCheckOrder = true;
2021 break;
2022 }
2023 }
2024 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002025 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002026
John McCallbb7b6582010-04-10 07:37:23 +00002027 // Build the list of bases and members in the order that they'll
2028 // actually be initialized. The explicit initializers should be in
2029 // this same order but may be missing things.
2030 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002031
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002032 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2033
John McCallbb7b6582010-04-10 07:37:23 +00002034 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002035 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002036 ClassDecl->vbases_begin(),
2037 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002038 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002039
John McCallbb7b6582010-04-10 07:37:23 +00002040 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002041 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002042 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002043 if (Base->isVirtual())
2044 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002045 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002046 }
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCallbb7b6582010-04-10 07:37:23 +00002048 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002049 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2050 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002051 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002052
John McCallbb7b6582010-04-10 07:37:23 +00002053 unsigned NumIdealInits = IdealInitKeys.size();
2054 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002055
John McCallbb7b6582010-04-10 07:37:23 +00002056 CXXBaseOrMemberInitializer *PrevInit = 0;
2057 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2058 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002059 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002060
2061 // Scan forward to try to find this initializer in the idealized
2062 // initializers list.
2063 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2064 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002065 break;
John McCallbb7b6582010-04-10 07:37:23 +00002066
2067 // If we didn't find this initializer, it must be because we
2068 // scanned past it on a previous iteration. That can only
2069 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002070 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002071 Sema::SemaDiagnosticBuilder D =
2072 SemaRef.Diag(PrevInit->getSourceLocation(),
2073 diag::warn_initializer_out_of_order);
2074
Francois Pichetd583da02010-12-04 09:14:42 +00002075 if (PrevInit->isAnyMemberInitializer())
2076 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002077 else
2078 D << 1 << PrevInit->getBaseClassInfo()->getType();
2079
Francois Pichetd583da02010-12-04 09:14:42 +00002080 if (Init->isAnyMemberInitializer())
2081 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002082 else
2083 D << 1 << Init->getBaseClassInfo()->getType();
2084
2085 // Move back to the initializer's location in the ideal list.
2086 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2087 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002088 break;
John McCallbb7b6582010-04-10 07:37:23 +00002089
2090 assert(IdealIndex != NumIdealInits &&
2091 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002092 }
John McCallbb7b6582010-04-10 07:37:23 +00002093
2094 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002095 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002096}
2097
John McCall23eebd92010-04-10 09:28:51 +00002098namespace {
2099bool CheckRedundantInit(Sema &S,
2100 CXXBaseOrMemberInitializer *Init,
2101 CXXBaseOrMemberInitializer *&PrevInit) {
2102 if (!PrevInit) {
2103 PrevInit = Init;
2104 return false;
2105 }
2106
2107 if (FieldDecl *Field = Init->getMember())
2108 S.Diag(Init->getSourceLocation(),
2109 diag::err_multiple_mem_initialization)
2110 << Field->getDeclName()
2111 << Init->getSourceRange();
2112 else {
2113 Type *BaseClass = Init->getBaseClass();
2114 assert(BaseClass && "neither field nor base");
2115 S.Diag(Init->getSourceLocation(),
2116 diag::err_multiple_base_initialization)
2117 << QualType(BaseClass, 0)
2118 << Init->getSourceRange();
2119 }
2120 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2121 << 0 << PrevInit->getSourceRange();
2122
2123 return true;
2124}
2125
2126typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2127typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2128
2129bool CheckRedundantUnionInit(Sema &S,
2130 CXXBaseOrMemberInitializer *Init,
2131 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002132 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002133 RecordDecl *Parent = Field->getParent();
2134 if (!Parent->isAnonymousStructOrUnion())
2135 return false;
2136
2137 NamedDecl *Child = Field;
2138 do {
2139 if (Parent->isUnion()) {
2140 UnionEntry &En = Unions[Parent];
2141 if (En.first && En.first != Child) {
2142 S.Diag(Init->getSourceLocation(),
2143 diag::err_multiple_mem_union_initialization)
2144 << Field->getDeclName()
2145 << Init->getSourceRange();
2146 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2147 << 0 << En.second->getSourceRange();
2148 return true;
2149 } else if (!En.first) {
2150 En.first = Child;
2151 En.second = Init;
2152 }
2153 }
2154
2155 Child = Parent;
2156 Parent = cast<RecordDecl>(Parent->getDeclContext());
2157 } while (Parent->isAnonymousStructOrUnion());
2158
2159 return false;
2160}
2161}
2162
Anders Carlssone857b292010-04-02 03:37:03 +00002163/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002164void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002165 SourceLocation ColonLoc,
2166 MemInitTy **meminits, unsigned NumMemInits,
2167 bool AnyErrors) {
2168 if (!ConstructorDecl)
2169 return;
2170
2171 AdjustDeclIfTemplate(ConstructorDecl);
2172
2173 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002174 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002175
2176 if (!Constructor) {
2177 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2178 return;
2179 }
2180
2181 CXXBaseOrMemberInitializer **MemInits =
2182 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002183
2184 // Mapping for the duplicate initializers check.
2185 // For member initializers, this is keyed with a FieldDecl*.
2186 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002187 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002188
2189 // Mapping for the inconsistent anonymous-union initializers check.
2190 RedundantUnionMap MemberUnions;
2191
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002192 bool HadError = false;
2193 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002194 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002195
Abramo Bagnara341d7832010-05-26 18:09:23 +00002196 // Set the source order index.
2197 Init->setSourceOrder(i);
2198
Francois Pichetd583da02010-12-04 09:14:42 +00002199 if (Init->isAnyMemberInitializer()) {
2200 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002201 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2202 CheckRedundantUnionInit(*this, Init, MemberUnions))
2203 HadError = true;
2204 } else {
2205 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2206 if (CheckRedundantInit(*this, Init, Members[Key]))
2207 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002208 }
Anders Carlssone857b292010-04-02 03:37:03 +00002209 }
2210
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002211 if (HadError)
2212 return;
2213
Anders Carlssone857b292010-04-02 03:37:03 +00002214 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002215
2216 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002217}
2218
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002219void
John McCalla6309952010-03-16 21:39:52 +00002220Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2221 CXXRecordDecl *ClassDecl) {
2222 // Ignore dependent contexts.
2223 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002224 return;
John McCall1064d7e2010-03-16 05:22:47 +00002225
2226 // FIXME: all the access-control diagnostics are positioned on the
2227 // field/base declaration. That's probably good; that said, the
2228 // user might reasonably want to know why the destructor is being
2229 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002230
Anders Carlssondee9a302009-11-17 04:44:12 +00002231 // Non-static data members.
2232 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2233 E = ClassDecl->field_end(); I != E; ++I) {
2234 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002235 if (Field->isInvalidDecl())
2236 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002237 QualType FieldType = Context.getBaseElementType(Field->getType());
2238
2239 const RecordType* RT = FieldType->getAs<RecordType>();
2240 if (!RT)
2241 continue;
2242
2243 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2244 if (FieldClassDecl->hasTrivialDestructor())
2245 continue;
2246
Douglas Gregore71edda2010-07-01 22:47:18 +00002247 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002248 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002249 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002250 << Field->getDeclName()
2251 << FieldType);
2252
John McCalla6309952010-03-16 21:39:52 +00002253 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002254 }
2255
John McCall1064d7e2010-03-16 05:22:47 +00002256 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2257
Anders Carlssondee9a302009-11-17 04:44:12 +00002258 // Bases.
2259 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2260 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002261 // Bases are always records in a well-formed non-dependent class.
2262 const RecordType *RT = Base->getType()->getAs<RecordType>();
2263
2264 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002265 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002266 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002267
2268 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002269 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002270 if (BaseClassDecl->hasTrivialDestructor())
2271 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002272
Douglas Gregore71edda2010-07-01 22:47:18 +00002273 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002274
2275 // FIXME: caret should be on the start of the class name
2276 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002277 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002278 << Base->getType()
2279 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002280
John McCalla6309952010-03-16 21:39:52 +00002281 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002282 }
2283
2284 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002285 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2286 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002287
2288 // Bases are always records in a well-formed non-dependent class.
2289 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2290
2291 // Ignore direct virtual bases.
2292 if (DirectVirtualBases.count(RT))
2293 continue;
2294
Anders Carlssondee9a302009-11-17 04:44:12 +00002295 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002296 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002297 if (BaseClassDecl->hasTrivialDestructor())
2298 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002299
Douglas Gregore71edda2010-07-01 22:47:18 +00002300 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002301 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002302 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002303 << VBase->getType());
2304
John McCalla6309952010-03-16 21:39:52 +00002305 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002306 }
2307}
2308
John McCall48871652010-08-21 09:40:31 +00002309void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002310 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002311 return;
Mike Stump11289f42009-09-09 15:08:12 +00002312
Mike Stump11289f42009-09-09 15:08:12 +00002313 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002314 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002315 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002316}
2317
Mike Stump11289f42009-09-09 15:08:12 +00002318bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002319 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002320 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002321 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002322 else
John McCall02db245d2010-08-18 09:41:07 +00002323 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002324}
2325
Anders Carlssoneabf7702009-08-27 00:13:57 +00002326bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002327 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002328 if (!getLangOptions().CPlusPlus)
2329 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002330
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002331 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002332 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002333
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002334 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002335 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002336 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002337 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002338
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002339 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002340 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002341 }
Mike Stump11289f42009-09-09 15:08:12 +00002342
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002343 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002344 if (!RT)
2345 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002346
John McCall67da35c2010-02-04 22:26:26 +00002347 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002348
John McCall02db245d2010-08-18 09:41:07 +00002349 // We can't answer whether something is abstract until it has a
2350 // definition. If it's currently being defined, we'll walk back
2351 // over all the declarations when we have a full definition.
2352 const CXXRecordDecl *Def = RD->getDefinition();
2353 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002354 return false;
2355
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002356 if (!RD->isAbstract())
2357 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002358
Anders Carlssoneabf7702009-08-27 00:13:57 +00002359 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002360 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002361
John McCall02db245d2010-08-18 09:41:07 +00002362 return true;
2363}
2364
2365void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2366 // Check if we've already emitted the list of pure virtual functions
2367 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002368 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002369 return;
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregor4165bd62010-03-23 23:47:56 +00002371 CXXFinalOverriderMap FinalOverriders;
2372 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002373
Anders Carlssona2f74f32010-06-03 01:00:02 +00002374 // Keep a set of seen pure methods so we won't diagnose the same method
2375 // more than once.
2376 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2377
Douglas Gregor4165bd62010-03-23 23:47:56 +00002378 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2379 MEnd = FinalOverriders.end();
2380 M != MEnd;
2381 ++M) {
2382 for (OverridingMethods::iterator SO = M->second.begin(),
2383 SOEnd = M->second.end();
2384 SO != SOEnd; ++SO) {
2385 // C++ [class.abstract]p4:
2386 // A class is abstract if it contains or inherits at least one
2387 // pure virtual function for which the final overrider is pure
2388 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002389
Douglas Gregor4165bd62010-03-23 23:47:56 +00002390 //
2391 if (SO->second.size() != 1)
2392 continue;
2393
2394 if (!SO->second.front().Method->isPure())
2395 continue;
2396
Anders Carlssona2f74f32010-06-03 01:00:02 +00002397 if (!SeenPureMethods.insert(SO->second.front().Method))
2398 continue;
2399
Douglas Gregor4165bd62010-03-23 23:47:56 +00002400 Diag(SO->second.front().Method->getLocation(),
2401 diag::note_pure_virtual_function)
2402 << SO->second.front().Method->getDeclName();
2403 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002404 }
2405
2406 if (!PureVirtualClassDiagSet)
2407 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2408 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002409}
2410
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002411namespace {
John McCall02db245d2010-08-18 09:41:07 +00002412struct AbstractUsageInfo {
2413 Sema &S;
2414 CXXRecordDecl *Record;
2415 CanQualType AbstractType;
2416 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002417
John McCall02db245d2010-08-18 09:41:07 +00002418 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2419 : S(S), Record(Record),
2420 AbstractType(S.Context.getCanonicalType(
2421 S.Context.getTypeDeclType(Record))),
2422 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002423
John McCall02db245d2010-08-18 09:41:07 +00002424 void DiagnoseAbstractType() {
2425 if (Invalid) return;
2426 S.DiagnoseAbstractType(Record);
2427 Invalid = true;
2428 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002429
John McCall02db245d2010-08-18 09:41:07 +00002430 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2431};
2432
2433struct CheckAbstractUsage {
2434 AbstractUsageInfo &Info;
2435 const NamedDecl *Ctx;
2436
2437 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2438 : Info(Info), Ctx(Ctx) {}
2439
2440 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2441 switch (TL.getTypeLocClass()) {
2442#define ABSTRACT_TYPELOC(CLASS, PARENT)
2443#define TYPELOC(CLASS, PARENT) \
2444 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2445#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002446 }
John McCall02db245d2010-08-18 09:41:07 +00002447 }
Mike Stump11289f42009-09-09 15:08:12 +00002448
John McCall02db245d2010-08-18 09:41:07 +00002449 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2450 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2451 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2452 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2453 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002454 }
John McCall02db245d2010-08-18 09:41:07 +00002455 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002456
John McCall02db245d2010-08-18 09:41:07 +00002457 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2458 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
John McCall02db245d2010-08-18 09:41:07 +00002461 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2462 // Visit the type parameters from a permissive context.
2463 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2464 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2465 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2466 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2467 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2468 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002469 }
John McCall02db245d2010-08-18 09:41:07 +00002470 }
Mike Stump11289f42009-09-09 15:08:12 +00002471
John McCall02db245d2010-08-18 09:41:07 +00002472 // Visit pointee types from a permissive context.
2473#define CheckPolymorphic(Type) \
2474 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2475 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2476 }
2477 CheckPolymorphic(PointerTypeLoc)
2478 CheckPolymorphic(ReferenceTypeLoc)
2479 CheckPolymorphic(MemberPointerTypeLoc)
2480 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002481
John McCall02db245d2010-08-18 09:41:07 +00002482 /// Handle all the types we haven't given a more specific
2483 /// implementation for above.
2484 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2485 // Every other kind of type that we haven't called out already
2486 // that has an inner type is either (1) sugar or (2) contains that
2487 // inner type in some way as a subobject.
2488 if (TypeLoc Next = TL.getNextTypeLoc())
2489 return Visit(Next, Sel);
2490
2491 // If there's no inner type and we're in a permissive context,
2492 // don't diagnose.
2493 if (Sel == Sema::AbstractNone) return;
2494
2495 // Check whether the type matches the abstract type.
2496 QualType T = TL.getType();
2497 if (T->isArrayType()) {
2498 Sel = Sema::AbstractArrayType;
2499 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002500 }
John McCall02db245d2010-08-18 09:41:07 +00002501 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2502 if (CT != Info.AbstractType) return;
2503
2504 // It matched; do some magic.
2505 if (Sel == Sema::AbstractArrayType) {
2506 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2507 << T << TL.getSourceRange();
2508 } else {
2509 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2510 << Sel << T << TL.getSourceRange();
2511 }
2512 Info.DiagnoseAbstractType();
2513 }
2514};
2515
2516void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2517 Sema::AbstractDiagSelID Sel) {
2518 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2519}
2520
2521}
2522
2523/// Check for invalid uses of an abstract type in a method declaration.
2524static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2525 CXXMethodDecl *MD) {
2526 // No need to do the check on definitions, which require that
2527 // the return/param types be complete.
2528 if (MD->isThisDeclarationADefinition())
2529 return;
2530
2531 // For safety's sake, just ignore it if we don't have type source
2532 // information. This should never happen for non-implicit methods,
2533 // but...
2534 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2535 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2536}
2537
2538/// Check for invalid uses of an abstract type within a class definition.
2539static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2540 CXXRecordDecl *RD) {
2541 for (CXXRecordDecl::decl_iterator
2542 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2543 Decl *D = *I;
2544 if (D->isImplicit()) continue;
2545
2546 // Methods and method templates.
2547 if (isa<CXXMethodDecl>(D)) {
2548 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2549 } else if (isa<FunctionTemplateDecl>(D)) {
2550 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2551 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2552
2553 // Fields and static variables.
2554 } else if (isa<FieldDecl>(D)) {
2555 FieldDecl *FD = cast<FieldDecl>(D);
2556 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2557 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2558 } else if (isa<VarDecl>(D)) {
2559 VarDecl *VD = cast<VarDecl>(D);
2560 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2561 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2562
2563 // Nested classes and class templates.
2564 } else if (isa<CXXRecordDecl>(D)) {
2565 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2566 } else if (isa<ClassTemplateDecl>(D)) {
2567 CheckAbstractClassUsage(Info,
2568 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2569 }
2570 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002571}
2572
Douglas Gregorc99f1552009-12-03 18:33:45 +00002573/// \brief Perform semantic checks on a class definition that has been
2574/// completing, introducing implicitly-declared members, checking for
2575/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002576void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002577 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002578 return;
2579
John McCall02db245d2010-08-18 09:41:07 +00002580 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2581 AbstractUsageInfo Info(*this, Record);
2582 CheckAbstractClassUsage(Info, Record);
2583 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002584
2585 // If this is not an aggregate type and has no user-declared constructor,
2586 // complain about any non-static data members of reference or const scalar
2587 // type, since they will never get initializers.
2588 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2589 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2590 bool Complained = false;
2591 for (RecordDecl::field_iterator F = Record->field_begin(),
2592 FEnd = Record->field_end();
2593 F != FEnd; ++F) {
2594 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002595 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002596 if (!Complained) {
2597 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2598 << Record->getTagKind() << Record;
2599 Complained = true;
2600 }
2601
2602 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2603 << F->getType()->isReferenceType()
2604 << F->getDeclName();
2605 }
2606 }
2607 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002608
2609 if (Record->isDynamicClass())
2610 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002611
2612 if (Record->getIdentifier()) {
2613 // C++ [class.mem]p13:
2614 // If T is the name of a class, then each of the following shall have a
2615 // name different from T:
2616 // - every member of every anonymous union that is a member of class T.
2617 //
2618 // C++ [class.mem]p14:
2619 // In addition, if class T has a user-declared constructor (12.1), every
2620 // non-static data member of class T shall have a name different from T.
2621 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002622 R.first != R.second; ++R.first) {
2623 NamedDecl *D = *R.first;
2624 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2625 isa<IndirectFieldDecl>(D)) {
2626 Diag(D->getLocation(), diag::err_member_name_of_class)
2627 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002628 break;
2629 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002630 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002631 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002632}
2633
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002634void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002635 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002636 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002637 SourceLocation RBrac,
2638 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002639 if (!TagDecl)
2640 return;
Mike Stump11289f42009-09-09 15:08:12 +00002641
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002642 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002643
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002644 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002645 // strict aliasing violation!
2646 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002647 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002648
Douglas Gregor0be31a22010-07-02 17:43:08 +00002649 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002650 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002651}
2652
Douglas Gregor95755162010-07-01 05:10:53 +00002653namespace {
2654 /// \brief Helper class that collects exception specifications for
2655 /// implicitly-declared special member functions.
2656 class ImplicitExceptionSpecification {
2657 ASTContext &Context;
2658 bool AllowsAllExceptions;
2659 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2660 llvm::SmallVector<QualType, 4> Exceptions;
2661
2662 public:
2663 explicit ImplicitExceptionSpecification(ASTContext &Context)
2664 : Context(Context), AllowsAllExceptions(false) { }
2665
2666 /// \brief Whether the special member function should have any
2667 /// exception specification at all.
2668 bool hasExceptionSpecification() const {
2669 return !AllowsAllExceptions;
2670 }
2671
2672 /// \brief Whether the special member function should have a
2673 /// throw(...) exception specification (a Microsoft extension).
2674 bool hasAnyExceptionSpecification() const {
2675 return false;
2676 }
2677
2678 /// \brief The number of exceptions in the exception specification.
2679 unsigned size() const { return Exceptions.size(); }
2680
2681 /// \brief The set of exceptions in the exception specification.
2682 const QualType *data() const { return Exceptions.data(); }
2683
2684 /// \brief Note that
2685 void CalledDecl(CXXMethodDecl *Method) {
2686 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002687 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002688 return;
2689
2690 const FunctionProtoType *Proto
2691 = Method->getType()->getAs<FunctionProtoType>();
2692
2693 // If this function can throw any exceptions, make a note of that.
2694 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2695 AllowsAllExceptions = true;
2696 ExceptionsSeen.clear();
2697 Exceptions.clear();
2698 return;
2699 }
2700
2701 // Record the exceptions in this function's exception specification.
2702 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2703 EEnd = Proto->exception_end();
2704 E != EEnd; ++E)
2705 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2706 Exceptions.push_back(*E);
2707 }
2708 };
2709}
2710
2711
Douglas Gregor05379422008-11-03 17:51:48 +00002712/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2713/// special functions, such as the default constructor, copy
2714/// constructor, or destructor, to the given C++ class (C++
2715/// [special]p1). This routine can only be executed just before the
2716/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002717void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002718 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002719 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002720
Douglas Gregor54be3392010-07-01 17:57:27 +00002721 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002722 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002723
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002724 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2725 ++ASTContext::NumImplicitCopyAssignmentOperators;
2726
2727 // If we have a dynamic class, then the copy assignment operator may be
2728 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2729 // it shows up in the right place in the vtable and that we diagnose
2730 // problems with the implicit exception specification.
2731 if (ClassDecl->isDynamicClass())
2732 DeclareImplicitCopyAssignment(ClassDecl);
2733 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002734
Douglas Gregor7454c562010-07-02 20:37:36 +00002735 if (!ClassDecl->hasUserDeclaredDestructor()) {
2736 ++ASTContext::NumImplicitDestructors;
2737
2738 // If we have a dynamic class, then the destructor may be virtual, so we
2739 // have to declare the destructor immediately. This ensures that, e.g., it
2740 // shows up in the right place in the vtable and that we diagnose problems
2741 // with the implicit exception specification.
2742 if (ClassDecl->isDynamicClass())
2743 DeclareImplicitDestructor(ClassDecl);
2744 }
Douglas Gregor05379422008-11-03 17:51:48 +00002745}
2746
John McCall48871652010-08-21 09:40:31 +00002747void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002748 if (!D)
2749 return;
2750
2751 TemplateParameterList *Params = 0;
2752 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2753 Params = Template->getTemplateParameters();
2754 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2755 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2756 Params = PartialSpec->getTemplateParameters();
2757 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002758 return;
2759
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002760 for (TemplateParameterList::iterator Param = Params->begin(),
2761 ParamEnd = Params->end();
2762 Param != ParamEnd; ++Param) {
2763 NamedDecl *Named = cast<NamedDecl>(*Param);
2764 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002765 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002766 IdResolver.AddDecl(Named);
2767 }
2768 }
2769}
2770
John McCall48871652010-08-21 09:40:31 +00002771void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002772 if (!RecordD) return;
2773 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002774 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002775 PushDeclContext(S, Record);
2776}
2777
John McCall48871652010-08-21 09:40:31 +00002778void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002779 if (!RecordD) return;
2780 PopDeclContext();
2781}
2782
Douglas Gregor4d87df52008-12-16 21:30:33 +00002783/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2784/// parsing a top-level (non-nested) C++ class, and we are now
2785/// parsing those parts of the given Method declaration that could
2786/// not be parsed earlier (C++ [class.mem]p2), such as default
2787/// arguments. This action should enter the scope of the given
2788/// Method declaration as if we had just parsed the qualified method
2789/// name. However, it should not bring the parameters into scope;
2790/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002791void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002792}
2793
2794/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2795/// C++ method declaration. We're (re-)introducing the given
2796/// function parameter into scope for use in parsing later parts of
2797/// the method declaration. For example, we could see an
2798/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002799void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002800 if (!ParamD)
2801 return;
Mike Stump11289f42009-09-09 15:08:12 +00002802
John McCall48871652010-08-21 09:40:31 +00002803 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002804
2805 // If this parameter has an unparsed default argument, clear it out
2806 // to make way for the parsed default argument.
2807 if (Param->hasUnparsedDefaultArg())
2808 Param->setDefaultArg(0);
2809
John McCall48871652010-08-21 09:40:31 +00002810 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002811 if (Param->getDeclName())
2812 IdResolver.AddDecl(Param);
2813}
2814
2815/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2816/// processing the delayed method declaration for Method. The method
2817/// declaration is now considered finished. There may be a separate
2818/// ActOnStartOfFunctionDef action later (not necessarily
2819/// immediately!) for this method, if it was also defined inside the
2820/// class body.
John McCall48871652010-08-21 09:40:31 +00002821void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002822 if (!MethodD)
2823 return;
Mike Stump11289f42009-09-09 15:08:12 +00002824
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002825 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002826
John McCall48871652010-08-21 09:40:31 +00002827 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002828
2829 // Now that we have our default arguments, check the constructor
2830 // again. It could produce additional diagnostics or affect whether
2831 // the class has implicitly-declared destructors, among other
2832 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002833 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2834 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002835
2836 // Check the default arguments, which we may have added.
2837 if (!Method->isInvalidDecl())
2838 CheckCXXDefaultArguments(Method);
2839}
2840
Douglas Gregor831c93f2008-11-05 20:51:48 +00002841/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002842/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002843/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002844/// emit diagnostics and set the invalid bit to true. In any case, the type
2845/// will be updated to reflect a well-formed type for the constructor and
2846/// returned.
2847QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002848 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002849 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002850
2851 // C++ [class.ctor]p3:
2852 // A constructor shall not be virtual (10.3) or static (9.4). A
2853 // constructor can be invoked for a const, volatile or const
2854 // volatile object. A constructor shall not be declared const,
2855 // volatile, or const volatile (9.3.2).
2856 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002857 if (!D.isInvalidType())
2858 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2859 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2860 << SourceRange(D.getIdentifierLoc());
2861 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002862 }
John McCall8e7d6562010-08-26 03:08:43 +00002863 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002864 if (!D.isInvalidType())
2865 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2866 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2867 << SourceRange(D.getIdentifierLoc());
2868 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002869 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002870 }
Mike Stump11289f42009-09-09 15:08:12 +00002871
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002872 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002873 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002874 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002875 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2876 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002877 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002878 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2879 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002880 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002881 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2882 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002883 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002884 }
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregor831c93f2008-11-05 20:51:48 +00002886 // Rebuild the function type "R" without any type qualifiers (in
2887 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002888 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002889 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002890 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2891 return R;
2892
2893 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2894 EPI.TypeQuals = 0;
2895
Chris Lattner38378bf2009-04-25 08:28:21 +00002896 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002897 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002898}
2899
Douglas Gregor4d87df52008-12-16 21:30:33 +00002900/// CheckConstructor - Checks a fully-formed constructor for
2901/// well-formedness, issuing any diagnostics required. Returns true if
2902/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002903void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002904 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002905 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2906 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002907 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002908
2909 // C++ [class.copy]p3:
2910 // A declaration of a constructor for a class X is ill-formed if
2911 // its first parameter is of type (optionally cv-qualified) X and
2912 // either there are no other parameters or else all other
2913 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002914 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002915 ((Constructor->getNumParams() == 1) ||
2916 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002917 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2918 Constructor->getTemplateSpecializationKind()
2919 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002920 QualType ParamType = Constructor->getParamDecl(0)->getType();
2921 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2922 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002923 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002924 const char *ConstRef
2925 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2926 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002927 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002928 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002929
2930 // FIXME: Rather that making the constructor invalid, we should endeavor
2931 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002932 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002933 }
2934 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002935}
2936
John McCalldeb646e2010-08-04 01:04:25 +00002937/// CheckDestructor - Checks a fully-formed destructor definition for
2938/// well-formedness, issuing any diagnostics required. Returns true
2939/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002940bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002941 CXXRecordDecl *RD = Destructor->getParent();
2942
2943 if (Destructor->isVirtual()) {
2944 SourceLocation Loc;
2945
2946 if (!Destructor->isImplicit())
2947 Loc = Destructor->getLocation();
2948 else
2949 Loc = RD->getLocation();
2950
2951 // If we have a virtual destructor, look up the deallocation function
2952 FunctionDecl *OperatorDelete = 0;
2953 DeclarationName Name =
2954 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002955 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002956 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002957
2958 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002959
2960 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002961 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002962
2963 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002964}
2965
Mike Stump11289f42009-09-09 15:08:12 +00002966static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002967FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2968 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2969 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002970 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002971}
2972
Douglas Gregor831c93f2008-11-05 20:51:48 +00002973/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2974/// the well-formednes of the destructor declarator @p D with type @p
2975/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002976/// emit diagnostics and set the declarator to invalid. Even if this happens,
2977/// will be updated to reflect a well-formed type for the destructor and
2978/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002979QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002980 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002981 // C++ [class.dtor]p1:
2982 // [...] A typedef-name that names a class is a class-name
2983 // (7.1.3); however, a typedef-name that names a class shall not
2984 // be used as the identifier in the declarator for a destructor
2985 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002986 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002987 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002988 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002989 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002990
2991 // C++ [class.dtor]p2:
2992 // A destructor is used to destroy objects of its class type. A
2993 // destructor takes no parameters, and no return type can be
2994 // specified for it (not even void). The address of a destructor
2995 // shall not be taken. A destructor shall not be static. A
2996 // destructor can be invoked for a const, volatile or const
2997 // volatile object. A destructor shall not be declared const,
2998 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002999 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003000 if (!D.isInvalidType())
3001 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3002 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003003 << SourceRange(D.getIdentifierLoc())
3004 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3005
John McCall8e7d6562010-08-26 03:08:43 +00003006 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003007 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003008 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003009 // Destructors don't have return types, but the parser will
3010 // happily parse something like:
3011 //
3012 // class X {
3013 // float ~X();
3014 // };
3015 //
3016 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003017 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3018 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3019 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003020 }
Mike Stump11289f42009-09-09 15:08:12 +00003021
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003022 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003023 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003024 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003025 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3026 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003027 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003028 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3029 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003030 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003031 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3032 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003033 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003034 }
3035
3036 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003037 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003038 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3039
3040 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003041 FTI.freeArgs();
3042 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003043 }
3044
Mike Stump11289f42009-09-09 15:08:12 +00003045 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003046 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003047 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003048 D.setInvalidType();
3049 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003050
3051 // Rebuild the function type "R" without any type qualifiers or
3052 // parameters (in case any of the errors above fired) and with
3053 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003054 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003055 if (!D.isInvalidType())
3056 return R;
3057
Douglas Gregor95755162010-07-01 05:10:53 +00003058 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003059 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3060 EPI.Variadic = false;
3061 EPI.TypeQuals = 0;
3062 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003063}
3064
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003065/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3066/// well-formednes of the conversion function declarator @p D with
3067/// type @p R. If there are any errors in the declarator, this routine
3068/// will emit diagnostics and return true. Otherwise, it will return
3069/// false. Either way, the type @p R will be updated to reflect a
3070/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003071void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003072 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003073 // C++ [class.conv.fct]p1:
3074 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003075 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003076 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003077 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003078 if (!D.isInvalidType())
3079 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3080 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3081 << SourceRange(D.getIdentifierLoc());
3082 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003083 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003084 }
John McCall212fa2e2010-04-13 00:04:31 +00003085
3086 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3087
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003088 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003089 // Conversion functions don't have return types, but the parser will
3090 // happily parse something like:
3091 //
3092 // class X {
3093 // float operator bool();
3094 // };
3095 //
3096 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003097 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3098 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3099 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003100 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003101 }
3102
John McCall212fa2e2010-04-13 00:04:31 +00003103 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3104
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003105 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003106 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003107 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3108
3109 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003110 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003111 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003112 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003113 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003114 D.setInvalidType();
3115 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003116
John McCall212fa2e2010-04-13 00:04:31 +00003117 // Diagnose "&operator bool()" and other such nonsense. This
3118 // is actually a gcc extension which we don't support.
3119 if (Proto->getResultType() != ConvType) {
3120 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3121 << Proto->getResultType();
3122 D.setInvalidType();
3123 ConvType = Proto->getResultType();
3124 }
3125
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003126 // C++ [class.conv.fct]p4:
3127 // The conversion-type-id shall not represent a function type nor
3128 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003129 if (ConvType->isArrayType()) {
3130 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3131 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003132 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003133 } else if (ConvType->isFunctionType()) {
3134 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3135 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003136 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003137 }
3138
3139 // Rebuild the function type "R" without any parameters (in case any
3140 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003141 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003142 if (D.isInvalidType())
3143 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003144
Douglas Gregor5fb53972009-01-14 15:45:31 +00003145 // C++0x explicit conversion operators.
3146 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003147 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003148 diag::warn_explicit_conversion_functions)
3149 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003150}
3151
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003152/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3153/// the declaration of the given C++ conversion function. This routine
3154/// is responsible for recording the conversion function in the C++
3155/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003156Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003157 assert(Conversion && "Expected to receive a conversion function declaration");
3158
Douglas Gregor4287b372008-12-12 08:25:50 +00003159 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003160
3161 // Make sure we aren't redeclaring the conversion function.
3162 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003163
3164 // C++ [class.conv.fct]p1:
3165 // [...] A conversion function is never used to convert a
3166 // (possibly cv-qualified) object to the (possibly cv-qualified)
3167 // same object type (or a reference to it), to a (possibly
3168 // cv-qualified) base class of that type (or a reference to it),
3169 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003170 // FIXME: Suppress this warning if the conversion function ends up being a
3171 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003172 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003174 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003175 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003176 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3177 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003178 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003179 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003180 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3181 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003182 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003183 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003184 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003185 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003186 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003187 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003188 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003189 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003190 }
3191
Douglas Gregor457104e2010-09-29 04:25:11 +00003192 if (FunctionTemplateDecl *ConversionTemplate
3193 = Conversion->getDescribedFunctionTemplate())
3194 return ConversionTemplate;
3195
John McCall48871652010-08-21 09:40:31 +00003196 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003197}
3198
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003199//===----------------------------------------------------------------------===//
3200// Namespace Handling
3201//===----------------------------------------------------------------------===//
3202
John McCallb1be5232010-08-26 09:15:37 +00003203
3204
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003205/// ActOnStartNamespaceDef - This is called at the start of a namespace
3206/// definition.
John McCall48871652010-08-21 09:40:31 +00003207Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003208 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003209 SourceLocation IdentLoc,
3210 IdentifierInfo *II,
3211 SourceLocation LBrace,
3212 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003213 // anonymous namespace starts at its left brace
3214 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3215 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003216 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003217 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003218
3219 Scope *DeclRegionScope = NamespcScope->getParent();
3220
Anders Carlssona7bcade2010-02-07 01:09:23 +00003221 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3222
John McCall2faf32c2010-12-10 02:59:44 +00003223 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3224 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003225
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003226 if (II) {
3227 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003228 // The identifier in an original-namespace-definition shall not
3229 // have been previously defined in the declarative region in
3230 // which the original-namespace-definition appears. The
3231 // identifier in an original-namespace-definition is the name of
3232 // the namespace. Subsequently in that declarative region, it is
3233 // treated as an original-namespace-name.
3234 //
3235 // Since namespace names are unique in their scope, and we don't
3236 // look through using directives, just
3237 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3238 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003239
Douglas Gregor91f84212008-12-11 16:49:14 +00003240 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3241 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003242 if (Namespc->isInline() != OrigNS->isInline()) {
3243 // inline-ness must match
3244 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3245 << Namespc->isInline();
3246 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3247 Namespc->setInvalidDecl();
3248 // Recover by ignoring the new namespace's inline status.
3249 Namespc->setInline(OrigNS->isInline());
3250 }
3251
Douglas Gregor91f84212008-12-11 16:49:14 +00003252 // Attach this namespace decl to the chain of extended namespace
3253 // definitions.
3254 OrigNS->setNextNamespace(Namespc);
3255 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003256
Mike Stump11289f42009-09-09 15:08:12 +00003257 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003258 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003259 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003260 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003261 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003262 } else if (PrevDecl) {
3263 // This is an invalid name redefinition.
3264 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3265 << Namespc->getDeclName();
3266 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3267 Namespc->setInvalidDecl();
3268 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003269 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003270 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003271 // This is the first "real" definition of the namespace "std", so update
3272 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003273 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003274 // We had already defined a dummy namespace "std". Link this new
3275 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003276 StdNS->setNextNamespace(Namespc);
3277 StdNS->setLocation(IdentLoc);
3278 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003279 }
3280
3281 // Make our StdNamespace cache point at the first real definition of the
3282 // "std" namespace.
3283 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003284 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003285
3286 PushOnScopeChains(Namespc, DeclRegionScope);
3287 } else {
John McCall4fa53422009-10-01 00:25:31 +00003288 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003289 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003290
3291 // Link the anonymous namespace into its parent.
3292 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003293 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003294 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3295 PrevDecl = TU->getAnonymousNamespace();
3296 TU->setAnonymousNamespace(Namespc);
3297 } else {
3298 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3299 PrevDecl = ND->getAnonymousNamespace();
3300 ND->setAnonymousNamespace(Namespc);
3301 }
3302
3303 // Link the anonymous namespace with its previous declaration.
3304 if (PrevDecl) {
3305 assert(PrevDecl->isAnonymousNamespace());
3306 assert(!PrevDecl->getNextNamespace());
3307 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3308 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003309
3310 if (Namespc->isInline() != PrevDecl->isInline()) {
3311 // inline-ness must match
3312 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3313 << Namespc->isInline();
3314 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3315 Namespc->setInvalidDecl();
3316 // Recover by ignoring the new namespace's inline status.
3317 Namespc->setInline(PrevDecl->isInline());
3318 }
John McCall0db42252009-12-16 02:06:49 +00003319 }
John McCall4fa53422009-10-01 00:25:31 +00003320
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003321 CurContext->addDecl(Namespc);
3322
John McCall4fa53422009-10-01 00:25:31 +00003323 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3324 // behaves as if it were replaced by
3325 // namespace unique { /* empty body */ }
3326 // using namespace unique;
3327 // namespace unique { namespace-body }
3328 // where all occurrences of 'unique' in a translation unit are
3329 // replaced by the same identifier and this identifier differs
3330 // from all other identifiers in the entire program.
3331
3332 // We just create the namespace with an empty name and then add an
3333 // implicit using declaration, just like the standard suggests.
3334 //
3335 // CodeGen enforces the "universally unique" aspect by giving all
3336 // declarations semantically contained within an anonymous
3337 // namespace internal linkage.
3338
John McCall0db42252009-12-16 02:06:49 +00003339 if (!PrevDecl) {
3340 UsingDirectiveDecl* UD
3341 = UsingDirectiveDecl::Create(Context, CurContext,
3342 /* 'using' */ LBrace,
3343 /* 'namespace' */ SourceLocation(),
3344 /* qualifier */ SourceRange(),
3345 /* NNS */ NULL,
3346 /* identifier */ SourceLocation(),
3347 Namespc,
3348 /* Ancestor */ CurContext);
3349 UD->setImplicit();
3350 CurContext->addDecl(UD);
3351 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003352 }
3353
3354 // Although we could have an invalid decl (i.e. the namespace name is a
3355 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003356 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3357 // for the namespace has the declarations that showed up in that particular
3358 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003359 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003360 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003361}
3362
Sebastian Redla6602e92009-11-23 15:34:23 +00003363/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3364/// is a namespace alias, returns the namespace it points to.
3365static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3366 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3367 return AD->getNamespace();
3368 return dyn_cast_or_null<NamespaceDecl>(D);
3369}
3370
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003371/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3372/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003373void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003374 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3375 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3376 Namespc->setRBracLoc(RBrace);
3377 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003378 if (Namespc->hasAttr<VisibilityAttr>())
3379 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003380}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003381
John McCall28a0cf72010-08-25 07:42:41 +00003382CXXRecordDecl *Sema::getStdBadAlloc() const {
3383 return cast_or_null<CXXRecordDecl>(
3384 StdBadAlloc.get(Context.getExternalSource()));
3385}
3386
3387NamespaceDecl *Sema::getStdNamespace() const {
3388 return cast_or_null<NamespaceDecl>(
3389 StdNamespace.get(Context.getExternalSource()));
3390}
3391
Douglas Gregorcdf87022010-06-29 17:53:46 +00003392/// \brief Retrieve the special "std" namespace, which may require us to
3393/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003394NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003395 if (!StdNamespace) {
3396 // The "std" namespace has not yet been defined, so build one implicitly.
3397 StdNamespace = NamespaceDecl::Create(Context,
3398 Context.getTranslationUnitDecl(),
3399 SourceLocation(),
3400 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003401 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003402 }
3403
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003404 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003405}
3406
John McCall48871652010-08-21 09:40:31 +00003407Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003408 SourceLocation UsingLoc,
3409 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003410 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003411 SourceLocation IdentLoc,
3412 IdentifierInfo *NamespcName,
3413 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003414 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3415 assert(NamespcName && "Invalid NamespcName.");
3416 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003417
3418 // This can only happen along a recovery path.
3419 while (S->getFlags() & Scope::TemplateParamScope)
3420 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003421 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003422
Douglas Gregor889ceb72009-02-03 19:21:40 +00003423 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003424 NestedNameSpecifier *Qualifier = 0;
3425 if (SS.isSet())
3426 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3427
Douglas Gregor34074322009-01-14 22:20:51 +00003428 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003429 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3430 LookupParsedName(R, S, &SS);
3431 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003432 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003433
Douglas Gregorcdf87022010-06-29 17:53:46 +00003434 if (R.empty()) {
3435 // Allow "using namespace std;" or "using namespace ::std;" even if
3436 // "std" hasn't been defined yet, for GCC compatibility.
3437 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3438 NamespcName->isStr("std")) {
3439 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003440 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003441 R.resolveKind();
3442 }
3443 // Otherwise, attempt typo correction.
3444 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3445 CTC_NoKeywords, 0)) {
3446 if (R.getAsSingle<NamespaceDecl>() ||
3447 R.getAsSingle<NamespaceAliasDecl>()) {
3448 if (DeclContext *DC = computeDeclContext(SS, false))
3449 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3450 << NamespcName << DC << Corrected << SS.getRange()
3451 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3452 else
3453 Diag(IdentLoc, diag::err_using_directive_suggest)
3454 << NamespcName << Corrected
3455 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3456 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3457 << Corrected;
3458
3459 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003460 } else {
3461 R.clear();
3462 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003463 }
3464 }
3465 }
3466
John McCall9f3059a2009-10-09 21:13:30 +00003467 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003468 NamedDecl *Named = R.getFoundDecl();
3469 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3470 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003471 // C++ [namespace.udir]p1:
3472 // A using-directive specifies that the names in the nominated
3473 // namespace can be used in the scope in which the
3474 // using-directive appears after the using-directive. During
3475 // unqualified name lookup (3.4.1), the names appear as if they
3476 // were declared in the nearest enclosing namespace which
3477 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003478 // namespace. [Note: in this context, "contains" means "contains
3479 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003480
3481 // Find enclosing context containing both using-directive and
3482 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003483 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003484 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3485 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3486 CommonAncestor = CommonAncestor->getParent();
3487
Sebastian Redla6602e92009-11-23 15:34:23 +00003488 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003489 SS.getRange(),
3490 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003491 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003492 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003493 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003494 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003495 }
3496
Douglas Gregor889ceb72009-02-03 19:21:40 +00003497 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003498 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003499}
3500
3501void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3502 // If scope has associated entity, then using directive is at namespace
3503 // or translation unit scope. We add UsingDirectiveDecls, into
3504 // it's lookup structure.
3505 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003506 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003507 else
3508 // Otherwise it is block-sope. using-directives will affect lookup
3509 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003510 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003511}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003512
Douglas Gregorfec52632009-06-20 00:51:54 +00003513
John McCall48871652010-08-21 09:40:31 +00003514Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003515 AccessSpecifier AS,
3516 bool HasUsingKeyword,
3517 SourceLocation UsingLoc,
3518 CXXScopeSpec &SS,
3519 UnqualifiedId &Name,
3520 AttributeList *AttrList,
3521 bool IsTypeName,
3522 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003523 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003524
Douglas Gregor220f4272009-11-04 16:30:06 +00003525 switch (Name.getKind()) {
3526 case UnqualifiedId::IK_Identifier:
3527 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003528 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003529 case UnqualifiedId::IK_ConversionFunctionId:
3530 break;
3531
3532 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003533 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003534 // C++0x inherited constructors.
3535 if (getLangOptions().CPlusPlus0x) break;
3536
Douglas Gregor220f4272009-11-04 16:30:06 +00003537 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3538 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003539 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003540
3541 case UnqualifiedId::IK_DestructorName:
3542 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3543 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003544 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003545
3546 case UnqualifiedId::IK_TemplateId:
3547 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3548 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003549 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003550 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003551
3552 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3553 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003554 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003555 return 0;
John McCall3969e302009-12-08 07:46:18 +00003556
John McCalla0097262009-12-11 02:10:03 +00003557 // Warn about using declarations.
3558 // TODO: store that the declaration was written without 'using' and
3559 // talk about access decls instead of using decls in the
3560 // diagnostics.
3561 if (!HasUsingKeyword) {
3562 UsingLoc = Name.getSourceRange().getBegin();
3563
3564 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003565 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003566 }
3567
Douglas Gregorc4356532010-12-16 00:46:58 +00003568 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3569 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3570 return 0;
3571
John McCall3f746822009-11-17 05:59:44 +00003572 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003573 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003574 /* IsInstantiation */ false,
3575 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003576 if (UD)
3577 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003578
John McCall48871652010-08-21 09:40:31 +00003579 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003580}
3581
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003582/// \brief Determine whether a using declaration considers the given
3583/// declarations as "equivalent", e.g., if they are redeclarations of
3584/// the same entity or are both typedefs of the same type.
3585static bool
3586IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3587 bool &SuppressRedeclaration) {
3588 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3589 SuppressRedeclaration = false;
3590 return true;
3591 }
3592
3593 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3594 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3595 SuppressRedeclaration = true;
3596 return Context.hasSameType(TD1->getUnderlyingType(),
3597 TD2->getUnderlyingType());
3598 }
3599
3600 return false;
3601}
3602
3603
John McCall84d87672009-12-10 09:41:52 +00003604/// Determines whether to create a using shadow decl for a particular
3605/// decl, given the set of decls existing prior to this using lookup.
3606bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3607 const LookupResult &Previous) {
3608 // Diagnose finding a decl which is not from a base class of the
3609 // current class. We do this now because there are cases where this
3610 // function will silently decide not to build a shadow decl, which
3611 // will pre-empt further diagnostics.
3612 //
3613 // We don't need to do this in C++0x because we do the check once on
3614 // the qualifier.
3615 //
3616 // FIXME: diagnose the following if we care enough:
3617 // struct A { int foo; };
3618 // struct B : A { using A::foo; };
3619 // template <class T> struct C : A {};
3620 // template <class T> struct D : C<T> { using B::foo; } // <---
3621 // This is invalid (during instantiation) in C++03 because B::foo
3622 // resolves to the using decl in B, which is not a base class of D<T>.
3623 // We can't diagnose it immediately because C<T> is an unknown
3624 // specialization. The UsingShadowDecl in D<T> then points directly
3625 // to A::foo, which will look well-formed when we instantiate.
3626 // The right solution is to not collapse the shadow-decl chain.
3627 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3628 DeclContext *OrigDC = Orig->getDeclContext();
3629
3630 // Handle enums and anonymous structs.
3631 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3632 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3633 while (OrigRec->isAnonymousStructOrUnion())
3634 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3635
3636 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3637 if (OrigDC == CurContext) {
3638 Diag(Using->getLocation(),
3639 diag::err_using_decl_nested_name_specifier_is_current_class)
3640 << Using->getNestedNameRange();
3641 Diag(Orig->getLocation(), diag::note_using_decl_target);
3642 return true;
3643 }
3644
3645 Diag(Using->getNestedNameRange().getBegin(),
3646 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3647 << Using->getTargetNestedNameDecl()
3648 << cast<CXXRecordDecl>(CurContext)
3649 << Using->getNestedNameRange();
3650 Diag(Orig->getLocation(), diag::note_using_decl_target);
3651 return true;
3652 }
3653 }
3654
3655 if (Previous.empty()) return false;
3656
3657 NamedDecl *Target = Orig;
3658 if (isa<UsingShadowDecl>(Target))
3659 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3660
John McCalla17e83e2009-12-11 02:33:26 +00003661 // If the target happens to be one of the previous declarations, we
3662 // don't have a conflict.
3663 //
3664 // FIXME: but we might be increasing its access, in which case we
3665 // should redeclare it.
3666 NamedDecl *NonTag = 0, *Tag = 0;
3667 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3668 I != E; ++I) {
3669 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003670 bool Result;
3671 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3672 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003673
3674 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3675 }
3676
John McCall84d87672009-12-10 09:41:52 +00003677 if (Target->isFunctionOrFunctionTemplate()) {
3678 FunctionDecl *FD;
3679 if (isa<FunctionTemplateDecl>(Target))
3680 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3681 else
3682 FD = cast<FunctionDecl>(Target);
3683
3684 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003685 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003686 case Ovl_Overload:
3687 return false;
3688
3689 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003690 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003691 break;
3692
3693 // We found a decl with the exact signature.
3694 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003695 // If we're in a record, we want to hide the target, so we
3696 // return true (without a diagnostic) to tell the caller not to
3697 // build a shadow decl.
3698 if (CurContext->isRecord())
3699 return true;
3700
3701 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003702 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003703 break;
3704 }
3705
3706 Diag(Target->getLocation(), diag::note_using_decl_target);
3707 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3708 return true;
3709 }
3710
3711 // Target is not a function.
3712
John McCall84d87672009-12-10 09:41:52 +00003713 if (isa<TagDecl>(Target)) {
3714 // No conflict between a tag and a non-tag.
3715 if (!Tag) return false;
3716
John McCalle29c5cd2009-12-10 19:51:03 +00003717 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003718 Diag(Target->getLocation(), diag::note_using_decl_target);
3719 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3720 return true;
3721 }
3722
3723 // No conflict between a tag and a non-tag.
3724 if (!NonTag) return false;
3725
John McCalle29c5cd2009-12-10 19:51:03 +00003726 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003727 Diag(Target->getLocation(), diag::note_using_decl_target);
3728 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3729 return true;
3730}
3731
John McCall3f746822009-11-17 05:59:44 +00003732/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003733UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003734 UsingDecl *UD,
3735 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003736
3737 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003738 NamedDecl *Target = Orig;
3739 if (isa<UsingShadowDecl>(Target)) {
3740 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3741 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003742 }
3743
3744 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003745 = UsingShadowDecl::Create(Context, CurContext,
3746 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003747 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003748
3749 Shadow->setAccess(UD->getAccess());
3750 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3751 Shadow->setInvalidDecl();
3752
John McCall3f746822009-11-17 05:59:44 +00003753 if (S)
John McCall3969e302009-12-08 07:46:18 +00003754 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003755 else
John McCall3969e302009-12-08 07:46:18 +00003756 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003757
John McCall3969e302009-12-08 07:46:18 +00003758
John McCall84d87672009-12-10 09:41:52 +00003759 return Shadow;
3760}
John McCall3969e302009-12-08 07:46:18 +00003761
John McCall84d87672009-12-10 09:41:52 +00003762/// Hides a using shadow declaration. This is required by the current
3763/// using-decl implementation when a resolvable using declaration in a
3764/// class is followed by a declaration which would hide or override
3765/// one or more of the using decl's targets; for example:
3766///
3767/// struct Base { void foo(int); };
3768/// struct Derived : Base {
3769/// using Base::foo;
3770/// void foo(int);
3771/// };
3772///
3773/// The governing language is C++03 [namespace.udecl]p12:
3774///
3775/// When a using-declaration brings names from a base class into a
3776/// derived class scope, member functions in the derived class
3777/// override and/or hide member functions with the same name and
3778/// parameter types in a base class (rather than conflicting).
3779///
3780/// There are two ways to implement this:
3781/// (1) optimistically create shadow decls when they're not hidden
3782/// by existing declarations, or
3783/// (2) don't create any shadow decls (or at least don't make them
3784/// visible) until we've fully parsed/instantiated the class.
3785/// The problem with (1) is that we might have to retroactively remove
3786/// a shadow decl, which requires several O(n) operations because the
3787/// decl structures are (very reasonably) not designed for removal.
3788/// (2) avoids this but is very fiddly and phase-dependent.
3789void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003790 if (Shadow->getDeclName().getNameKind() ==
3791 DeclarationName::CXXConversionFunctionName)
3792 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3793
John McCall84d87672009-12-10 09:41:52 +00003794 // Remove it from the DeclContext...
3795 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003796
John McCall84d87672009-12-10 09:41:52 +00003797 // ...and the scope, if applicable...
3798 if (S) {
John McCall48871652010-08-21 09:40:31 +00003799 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003800 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003801 }
3802
John McCall84d87672009-12-10 09:41:52 +00003803 // ...and the using decl.
3804 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3805
3806 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003807 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003808}
3809
John McCalle61f2ba2009-11-18 02:36:19 +00003810/// Builds a using declaration.
3811///
3812/// \param IsInstantiation - Whether this call arises from an
3813/// instantiation of an unresolved using declaration. We treat
3814/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003815NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3816 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003817 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003818 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003819 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003820 bool IsInstantiation,
3821 bool IsTypeName,
3822 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003823 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003824 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003825 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003826
Anders Carlssonf038fc22009-08-28 05:49:21 +00003827 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003828
Anders Carlsson59140b32009-08-28 03:16:11 +00003829 if (SS.isEmpty()) {
3830 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003831 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003832 }
Mike Stump11289f42009-09-09 15:08:12 +00003833
John McCall84d87672009-12-10 09:41:52 +00003834 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003835 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003836 ForRedeclaration);
3837 Previous.setHideTags(false);
3838 if (S) {
3839 LookupName(Previous, S);
3840
3841 // It is really dumb that we have to do this.
3842 LookupResult::Filter F = Previous.makeFilter();
3843 while (F.hasNext()) {
3844 NamedDecl *D = F.next();
3845 if (!isDeclInScope(D, CurContext, S))
3846 F.erase();
3847 }
3848 F.done();
3849 } else {
3850 assert(IsInstantiation && "no scope in non-instantiation");
3851 assert(CurContext->isRecord() && "scope not record in instantiation");
3852 LookupQualifiedName(Previous, CurContext);
3853 }
3854
Mike Stump11289f42009-09-09 15:08:12 +00003855 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003856 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3857
John McCall84d87672009-12-10 09:41:52 +00003858 // Check for invalid redeclarations.
3859 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3860 return 0;
3861
3862 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003863 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3864 return 0;
3865
John McCall84c16cf2009-11-12 03:15:40 +00003866 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003867 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003868 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003869 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003870 // FIXME: not all declaration name kinds are legal here
3871 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3872 UsingLoc, TypenameLoc,
3873 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003874 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003875 } else {
3876 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003877 UsingLoc, SS.getRange(),
3878 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003879 }
John McCallb96ec562009-12-04 22:46:56 +00003880 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003881 D = UsingDecl::Create(Context, CurContext,
3882 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003883 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003884 }
John McCallb96ec562009-12-04 22:46:56 +00003885 D->setAccess(AS);
3886 CurContext->addDecl(D);
3887
3888 if (!LookupContext) return D;
3889 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003890
John McCall0b66eb32010-05-01 00:40:08 +00003891 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003892 UD->setInvalidDecl();
3893 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003894 }
3895
John McCall3969e302009-12-08 07:46:18 +00003896 // Look up the target name.
3897
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003898 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003899
John McCall3969e302009-12-08 07:46:18 +00003900 // Unlike most lookups, we don't always want to hide tag
3901 // declarations: tag names are visible through the using declaration
3902 // even if hidden by ordinary names, *except* in a dependent context
3903 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003904 if (!IsInstantiation)
3905 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003906
John McCall27b18f82009-11-17 02:14:36 +00003907 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003908
John McCall9f3059a2009-10-09 21:13:30 +00003909 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003910 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003911 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003912 UD->setInvalidDecl();
3913 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003914 }
3915
John McCallb96ec562009-12-04 22:46:56 +00003916 if (R.isAmbiguous()) {
3917 UD->setInvalidDecl();
3918 return UD;
3919 }
Mike Stump11289f42009-09-09 15:08:12 +00003920
John McCalle61f2ba2009-11-18 02:36:19 +00003921 if (IsTypeName) {
3922 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003923 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003924 Diag(IdentLoc, diag::err_using_typename_non_type);
3925 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3926 Diag((*I)->getUnderlyingDecl()->getLocation(),
3927 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003928 UD->setInvalidDecl();
3929 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003930 }
3931 } else {
3932 // If we asked for a non-typename and we got a type, error out,
3933 // but only if this is an instantiation of an unresolved using
3934 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003935 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003936 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3937 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003938 UD->setInvalidDecl();
3939 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003940 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003941 }
3942
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003943 // C++0x N2914 [namespace.udecl]p6:
3944 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003945 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003946 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3947 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003948 UD->setInvalidDecl();
3949 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003950 }
Mike Stump11289f42009-09-09 15:08:12 +00003951
John McCall84d87672009-12-10 09:41:52 +00003952 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3953 if (!CheckUsingShadowDecl(UD, *I, Previous))
3954 BuildUsingShadowDecl(S, UD, *I);
3955 }
John McCall3f746822009-11-17 05:59:44 +00003956
3957 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003958}
3959
John McCall84d87672009-12-10 09:41:52 +00003960/// Checks that the given using declaration is not an invalid
3961/// redeclaration. Note that this is checking only for the using decl
3962/// itself, not for any ill-formedness among the UsingShadowDecls.
3963bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3964 bool isTypeName,
3965 const CXXScopeSpec &SS,
3966 SourceLocation NameLoc,
3967 const LookupResult &Prev) {
3968 // C++03 [namespace.udecl]p8:
3969 // C++0x [namespace.udecl]p10:
3970 // A using-declaration is a declaration and can therefore be used
3971 // repeatedly where (and only where) multiple declarations are
3972 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003973 //
John McCall032092f2010-11-29 18:01:58 +00003974 // That's in non-member contexts.
3975 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003976 return false;
3977
3978 NestedNameSpecifier *Qual
3979 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3980
3981 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3982 NamedDecl *D = *I;
3983
3984 bool DTypename;
3985 NestedNameSpecifier *DQual;
3986 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3987 DTypename = UD->isTypeName();
3988 DQual = UD->getTargetNestedNameDecl();
3989 } else if (UnresolvedUsingValueDecl *UD
3990 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3991 DTypename = false;
3992 DQual = UD->getTargetNestedNameSpecifier();
3993 } else if (UnresolvedUsingTypenameDecl *UD
3994 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3995 DTypename = true;
3996 DQual = UD->getTargetNestedNameSpecifier();
3997 } else continue;
3998
3999 // using decls differ if one says 'typename' and the other doesn't.
4000 // FIXME: non-dependent using decls?
4001 if (isTypeName != DTypename) continue;
4002
4003 // using decls differ if they name different scopes (but note that
4004 // template instantiation can cause this check to trigger when it
4005 // didn't before instantiation).
4006 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4007 Context.getCanonicalNestedNameSpecifier(DQual))
4008 continue;
4009
4010 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004011 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004012 return true;
4013 }
4014
4015 return false;
4016}
4017
John McCall3969e302009-12-08 07:46:18 +00004018
John McCallb96ec562009-12-04 22:46:56 +00004019/// Checks that the given nested-name qualifier used in a using decl
4020/// in the current context is appropriately related to the current
4021/// scope. If an error is found, diagnoses it and returns true.
4022bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4023 const CXXScopeSpec &SS,
4024 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004025 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004026
John McCall3969e302009-12-08 07:46:18 +00004027 if (!CurContext->isRecord()) {
4028 // C++03 [namespace.udecl]p3:
4029 // C++0x [namespace.udecl]p8:
4030 // A using-declaration for a class member shall be a member-declaration.
4031
4032 // If we weren't able to compute a valid scope, it must be a
4033 // dependent class scope.
4034 if (!NamedContext || NamedContext->isRecord()) {
4035 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4036 << SS.getRange();
4037 return true;
4038 }
4039
4040 // Otherwise, everything is known to be fine.
4041 return false;
4042 }
4043
4044 // The current scope is a record.
4045
4046 // If the named context is dependent, we can't decide much.
4047 if (!NamedContext) {
4048 // FIXME: in C++0x, we can diagnose if we can prove that the
4049 // nested-name-specifier does not refer to a base class, which is
4050 // still possible in some cases.
4051
4052 // Otherwise we have to conservatively report that things might be
4053 // okay.
4054 return false;
4055 }
4056
4057 if (!NamedContext->isRecord()) {
4058 // Ideally this would point at the last name in the specifier,
4059 // but we don't have that level of source info.
4060 Diag(SS.getRange().getBegin(),
4061 diag::err_using_decl_nested_name_specifier_is_not_class)
4062 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4063 return true;
4064 }
4065
Douglas Gregor7c842292010-12-21 07:41:49 +00004066 if (!NamedContext->isDependentContext() &&
4067 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4068 return true;
4069
John McCall3969e302009-12-08 07:46:18 +00004070 if (getLangOptions().CPlusPlus0x) {
4071 // C++0x [namespace.udecl]p3:
4072 // In a using-declaration used as a member-declaration, the
4073 // nested-name-specifier shall name a base class of the class
4074 // being defined.
4075
4076 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4077 cast<CXXRecordDecl>(NamedContext))) {
4078 if (CurContext == NamedContext) {
4079 Diag(NameLoc,
4080 diag::err_using_decl_nested_name_specifier_is_current_class)
4081 << SS.getRange();
4082 return true;
4083 }
4084
4085 Diag(SS.getRange().getBegin(),
4086 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4087 << (NestedNameSpecifier*) SS.getScopeRep()
4088 << cast<CXXRecordDecl>(CurContext)
4089 << SS.getRange();
4090 return true;
4091 }
4092
4093 return false;
4094 }
4095
4096 // C++03 [namespace.udecl]p4:
4097 // A using-declaration used as a member-declaration shall refer
4098 // to a member of a base class of the class being defined [etc.].
4099
4100 // Salient point: SS doesn't have to name a base class as long as
4101 // lookup only finds members from base classes. Therefore we can
4102 // diagnose here only if we can prove that that can't happen,
4103 // i.e. if the class hierarchies provably don't intersect.
4104
4105 // TODO: it would be nice if "definitely valid" results were cached
4106 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4107 // need to be repeated.
4108
4109 struct UserData {
4110 llvm::DenseSet<const CXXRecordDecl*> Bases;
4111
4112 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4113 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4114 Data->Bases.insert(Base);
4115 return true;
4116 }
4117
4118 bool hasDependentBases(const CXXRecordDecl *Class) {
4119 return !Class->forallBases(collect, this);
4120 }
4121
4122 /// Returns true if the base is dependent or is one of the
4123 /// accumulated base classes.
4124 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4125 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4126 return !Data->Bases.count(Base);
4127 }
4128
4129 bool mightShareBases(const CXXRecordDecl *Class) {
4130 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4131 }
4132 };
4133
4134 UserData Data;
4135
4136 // Returns false if we find a dependent base.
4137 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4138 return false;
4139
4140 // Returns false if the class has a dependent base or if it or one
4141 // of its bases is present in the base set of the current context.
4142 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4143 return false;
4144
4145 Diag(SS.getRange().getBegin(),
4146 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4147 << (NestedNameSpecifier*) SS.getScopeRep()
4148 << cast<CXXRecordDecl>(CurContext)
4149 << SS.getRange();
4150
4151 return true;
John McCallb96ec562009-12-04 22:46:56 +00004152}
4153
John McCall48871652010-08-21 09:40:31 +00004154Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004155 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004156 SourceLocation AliasLoc,
4157 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004158 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004159 SourceLocation IdentLoc,
4160 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004161
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004162 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004163 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4164 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004165
Anders Carlssondca83c42009-03-28 06:23:46 +00004166 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004167 NamedDecl *PrevDecl
4168 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4169 ForRedeclaration);
4170 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4171 PrevDecl = 0;
4172
4173 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004174 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004175 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004176 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004177 // FIXME: At some point, we'll want to create the (redundant)
4178 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004179 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004180 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004181 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004182 }
Mike Stump11289f42009-09-09 15:08:12 +00004183
Anders Carlssondca83c42009-03-28 06:23:46 +00004184 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4185 diag::err_redefinition_different_kind;
4186 Diag(AliasLoc, DiagID) << Alias;
4187 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004188 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004189 }
4190
John McCall27b18f82009-11-17 02:14:36 +00004191 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004192 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004193
John McCall9f3059a2009-10-09 21:13:30 +00004194 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004195 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4196 CTC_NoKeywords, 0)) {
4197 if (R.getAsSingle<NamespaceDecl>() ||
4198 R.getAsSingle<NamespaceAliasDecl>()) {
4199 if (DeclContext *DC = computeDeclContext(SS, false))
4200 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4201 << Ident << DC << Corrected << SS.getRange()
4202 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4203 else
4204 Diag(IdentLoc, diag::err_using_directive_suggest)
4205 << Ident << Corrected
4206 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4207
4208 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4209 << Corrected;
4210
4211 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004212 } else {
4213 R.clear();
4214 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004215 }
4216 }
4217
4218 if (R.empty()) {
4219 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004220 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004221 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004224 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004225 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4226 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004227 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004228 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004229
John McCalld8d0d432010-02-16 06:53:13 +00004230 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004231 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004232}
4233
Douglas Gregora57478e2010-05-01 15:04:51 +00004234namespace {
4235 /// \brief Scoped object used to handle the state changes required in Sema
4236 /// to implicitly define the body of a C++ member function;
4237 class ImplicitlyDefinedFunctionScope {
4238 Sema &S;
4239 DeclContext *PreviousContext;
4240
4241 public:
4242 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4243 : S(S), PreviousContext(S.CurContext)
4244 {
4245 S.CurContext = Method;
4246 S.PushFunctionScope();
4247 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4248 }
4249
4250 ~ImplicitlyDefinedFunctionScope() {
4251 S.PopExpressionEvaluationContext();
4252 S.PopFunctionOrBlockScope();
4253 S.CurContext = PreviousContext;
4254 }
4255 };
4256}
4257
Sebastian Redlc15c3262010-09-13 22:02:47 +00004258static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4259 CXXRecordDecl *D) {
4260 ASTContext &Context = Self.Context;
4261 QualType ClassType = Context.getTypeDeclType(D);
4262 DeclarationName ConstructorName
4263 = Context.DeclarationNames.getCXXConstructorName(
4264 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4265
4266 DeclContext::lookup_const_iterator Con, ConEnd;
4267 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4268 Con != ConEnd; ++Con) {
4269 // FIXME: In C++0x, a constructor template can be a default constructor.
4270 if (isa<FunctionTemplateDecl>(*Con))
4271 continue;
4272
4273 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4274 if (Constructor->isDefaultConstructor())
4275 return Constructor;
4276 }
4277 return 0;
4278}
4279
Douglas Gregor0be31a22010-07-02 17:43:08 +00004280CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4281 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004282 // C++ [class.ctor]p5:
4283 // A default constructor for a class X is a constructor of class X
4284 // that can be called without an argument. If there is no
4285 // user-declared constructor for class X, a default constructor is
4286 // implicitly declared. An implicitly-declared default constructor
4287 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004288 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4289 "Should not build implicit default constructor!");
4290
Douglas Gregor6d880b12010-07-01 22:31:05 +00004291 // C++ [except.spec]p14:
4292 // An implicitly declared special member function (Clause 12) shall have an
4293 // exception-specification. [...]
4294 ImplicitExceptionSpecification ExceptSpec(Context);
4295
4296 // Direct base-class destructors.
4297 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4298 BEnd = ClassDecl->bases_end();
4299 B != BEnd; ++B) {
4300 if (B->isVirtual()) // Handled below.
4301 continue;
4302
Douglas Gregor9672f922010-07-03 00:47:00 +00004303 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4304 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4305 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4306 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004307 else if (CXXConstructorDecl *Constructor
4308 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004309 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004310 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004311 }
4312
4313 // Virtual base-class destructors.
4314 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4315 BEnd = ClassDecl->vbases_end();
4316 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004317 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4318 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4319 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4320 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4321 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004322 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004323 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004324 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004325 }
4326
4327 // Field destructors.
4328 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4329 FEnd = ClassDecl->field_end();
4330 F != FEnd; ++F) {
4331 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004332 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4333 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4334 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4335 ExceptSpec.CalledDecl(
4336 DeclareImplicitDefaultConstructor(FieldClassDecl));
4337 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004338 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004339 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004340 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004341 }
John McCalldb40c7f2010-12-14 08:05:40 +00004342
4343 FunctionProtoType::ExtProtoInfo EPI;
4344 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4345 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4346 EPI.NumExceptions = ExceptSpec.size();
4347 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004348
4349 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004350 CanQualType ClassType
4351 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4352 DeclarationName Name
4353 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004354 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004355 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004356 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004357 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004358 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004359 /*TInfo=*/0,
4360 /*isExplicit=*/false,
4361 /*isInline=*/true,
4362 /*isImplicitlyDeclared=*/true);
4363 DefaultCon->setAccess(AS_public);
4364 DefaultCon->setImplicit();
4365 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004366
4367 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004368 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4369
Douglas Gregor0be31a22010-07-02 17:43:08 +00004370 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004371 PushOnScopeChains(DefaultCon, S, false);
4372 ClassDecl->addDecl(DefaultCon);
4373
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004374 return DefaultCon;
4375}
4376
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004377void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4378 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004379 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004380 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004381 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004382
Anders Carlsson423f5d82010-04-23 16:04:08 +00004383 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004384 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004385
Douglas Gregora57478e2010-05-01 15:04:51 +00004386 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004387 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor54818f02010-05-12 16:39:35 +00004388 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4389 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004390 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004391 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004392 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004393 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004394 }
Douglas Gregor73193272010-09-20 16:48:21 +00004395
4396 SourceLocation Loc = Constructor->getLocation();
4397 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4398
4399 Constructor->setUsed();
4400 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004401}
4402
Douglas Gregor0be31a22010-07-02 17:43:08 +00004403CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004404 // C++ [class.dtor]p2:
4405 // If a class has no user-declared destructor, a destructor is
4406 // declared implicitly. An implicitly-declared destructor is an
4407 // inline public member of its class.
4408
4409 // C++ [except.spec]p14:
4410 // An implicitly declared special member function (Clause 12) shall have
4411 // an exception-specification.
4412 ImplicitExceptionSpecification ExceptSpec(Context);
4413
4414 // Direct base-class destructors.
4415 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4416 BEnd = ClassDecl->bases_end();
4417 B != BEnd; ++B) {
4418 if (B->isVirtual()) // Handled below.
4419 continue;
4420
4421 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4422 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004423 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004424 }
4425
4426 // Virtual base-class destructors.
4427 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4428 BEnd = ClassDecl->vbases_end();
4429 B != BEnd; ++B) {
4430 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4431 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004432 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004433 }
4434
4435 // Field destructors.
4436 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4437 FEnd = ClassDecl->field_end();
4438 F != FEnd; ++F) {
4439 if (const RecordType *RecordTy
4440 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4441 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004442 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004443 }
4444
Douglas Gregor7454c562010-07-02 20:37:36 +00004445 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004446 FunctionProtoType::ExtProtoInfo EPI;
4447 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4448 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4449 EPI.NumExceptions = ExceptSpec.size();
4450 EPI.Exceptions = ExceptSpec.data();
4451 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004452
4453 CanQualType ClassType
4454 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4455 DeclarationName Name
4456 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004457 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004458 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004459 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004460 /*isInline=*/true,
4461 /*isImplicitlyDeclared=*/true);
4462 Destructor->setAccess(AS_public);
4463 Destructor->setImplicit();
4464 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004465
4466 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004467 ++ASTContext::NumImplicitDestructorsDeclared;
4468
4469 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004470 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004471 PushOnScopeChains(Destructor, S, false);
4472 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004473
4474 // This could be uniqued if it ever proves significant.
4475 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4476
4477 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004478
Douglas Gregorf1203042010-07-01 19:09:28 +00004479 return Destructor;
4480}
4481
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004482void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004483 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004484 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004485 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004486 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004487 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004488
Douglas Gregor54818f02010-05-12 16:39:35 +00004489 if (Destructor->isInvalidDecl())
4490 return;
4491
Douglas Gregora57478e2010-05-01 15:04:51 +00004492 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004493
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004494 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004495 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4496 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004497
Douglas Gregor54818f02010-05-12 16:39:35 +00004498 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004499 Diag(CurrentLocation, diag::note_member_synthesized_at)
4500 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4501
4502 Destructor->setInvalidDecl();
4503 return;
4504 }
4505
Douglas Gregor73193272010-09-20 16:48:21 +00004506 SourceLocation Loc = Destructor->getLocation();
4507 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4508
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004509 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004510 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004511}
4512
Douglas Gregorb139cd52010-05-01 20:49:11 +00004513/// \brief Builds a statement that copies the given entity from \p From to
4514/// \c To.
4515///
4516/// This routine is used to copy the members of a class with an
4517/// implicitly-declared copy assignment operator. When the entities being
4518/// copied are arrays, this routine builds for loops to copy them.
4519///
4520/// \param S The Sema object used for type-checking.
4521///
4522/// \param Loc The location where the implicit copy is being generated.
4523///
4524/// \param T The type of the expressions being copied. Both expressions must
4525/// have this type.
4526///
4527/// \param To The expression we are copying to.
4528///
4529/// \param From The expression we are copying from.
4530///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004531/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4532/// Otherwise, it's a non-static member subobject.
4533///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004534/// \param Depth Internal parameter recording the depth of the recursion.
4535///
4536/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004537static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004538BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004539 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004540 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004541 // C++0x [class.copy]p30:
4542 // Each subobject is assigned in the manner appropriate to its type:
4543 //
4544 // - if the subobject is of class type, the copy assignment operator
4545 // for the class is used (as if by explicit qualification; that is,
4546 // ignoring any possible virtual overriding functions in more derived
4547 // classes);
4548 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4549 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4550
4551 // Look for operator=.
4552 DeclarationName Name
4553 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4554 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4555 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4556
4557 // Filter out any result that isn't a copy-assignment operator.
4558 LookupResult::Filter F = OpLookup.makeFilter();
4559 while (F.hasNext()) {
4560 NamedDecl *D = F.next();
4561 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4562 if (Method->isCopyAssignmentOperator())
4563 continue;
4564
4565 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004566 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004567 F.done();
4568
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004569 // Suppress the protected check (C++ [class.protected]) for each of the
4570 // assignment operators we found. This strange dance is required when
4571 // we're assigning via a base classes's copy-assignment operator. To
4572 // ensure that we're getting the right base class subobject (without
4573 // ambiguities), we need to cast "this" to that subobject type; to
4574 // ensure that we don't go through the virtual call mechanism, we need
4575 // to qualify the operator= name with the base class (see below). However,
4576 // this means that if the base class has a protected copy assignment
4577 // operator, the protected member access check will fail. So, we
4578 // rewrite "protected" access to "public" access in this case, since we
4579 // know by construction that we're calling from a derived class.
4580 if (CopyingBaseSubobject) {
4581 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4582 L != LEnd; ++L) {
4583 if (L.getAccess() == AS_protected)
4584 L.setAccess(AS_public);
4585 }
4586 }
4587
Douglas Gregorb139cd52010-05-01 20:49:11 +00004588 // Create the nested-name-specifier that will be used to qualify the
4589 // reference to operator=; this is required to suppress the virtual
4590 // call mechanism.
4591 CXXScopeSpec SS;
4592 SS.setRange(Loc);
4593 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4594 T.getTypePtr()));
4595
4596 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004597 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004598 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004599 /*FirstQualifierInScope=*/0, OpLookup,
4600 /*TemplateArgs=*/0,
4601 /*SuppressQualifierCheck=*/true);
4602 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004603 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004604
4605 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004606
John McCalldadc5752010-08-24 06:29:42 +00004607 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004608 OpEqualRef.takeAs<Expr>(),
4609 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004610 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004611 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004612
4613 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004614 }
John McCallab8c2732010-03-16 06:11:48 +00004615
Douglas Gregorb139cd52010-05-01 20:49:11 +00004616 // - if the subobject is of scalar type, the built-in assignment
4617 // operator is used.
4618 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4619 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004620 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004621 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004622 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004623
4624 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004625 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004626
4627 // - if the subobject is an array, each element is assigned, in the
4628 // manner appropriate to the element type;
4629
4630 // Construct a loop over the array bounds, e.g.,
4631 //
4632 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4633 //
4634 // that will copy each of the array elements.
4635 QualType SizeType = S.Context.getSizeType();
4636
4637 // Create the iteration variable.
4638 IdentifierInfo *IterationVarName = 0;
4639 {
4640 llvm::SmallString<8> Str;
4641 llvm::raw_svector_ostream OS(Str);
4642 OS << "__i" << Depth;
4643 IterationVarName = &S.Context.Idents.get(OS.str());
4644 }
4645 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4646 IterationVarName, SizeType,
4647 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004648 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004649
4650 // Initialize the iteration variable to zero.
4651 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004652 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004653
4654 // Create a reference to the iteration variable; we'll use this several
4655 // times throughout.
4656 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004657 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004658 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4659
4660 // Create the DeclStmt that holds the iteration variable.
4661 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4662
4663 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004664 llvm::APInt Upper
4665 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004666 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004667 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004668 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4669 BO_NE, S.Context.BoolTy,
4670 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004671
4672 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004673 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004674 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4675 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004676
4677 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004678 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4679 IterationVarRef, Loc));
4680 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4681 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004682
4683 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004684 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4685 To, From, CopyingBaseSubobject,
4686 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004687 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004688 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004689
4690 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004691 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004692 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004693 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004694 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004695}
4696
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004697/// \brief Determine whether the given class has a copy assignment operator
4698/// that accepts a const-qualified argument.
4699static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4700 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4701
4702 if (!Class->hasDeclaredCopyAssignment())
4703 S.DeclareImplicitCopyAssignment(Class);
4704
4705 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4706 DeclarationName OpName
4707 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4708
4709 DeclContext::lookup_const_iterator Op, OpEnd;
4710 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4711 // C++ [class.copy]p9:
4712 // A user-declared copy assignment operator is a non-static non-template
4713 // member function of class X with exactly one parameter of type X, X&,
4714 // const X&, volatile X& or const volatile X&.
4715 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4716 if (!Method)
4717 continue;
4718
4719 if (Method->isStatic())
4720 continue;
4721 if (Method->getPrimaryTemplate())
4722 continue;
4723 const FunctionProtoType *FnType =
4724 Method->getType()->getAs<FunctionProtoType>();
4725 assert(FnType && "Overloaded operator has no prototype.");
4726 // Don't assert on this; an invalid decl might have been left in the AST.
4727 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4728 continue;
4729 bool AcceptsConst = true;
4730 QualType ArgType = FnType->getArgType(0);
4731 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4732 ArgType = Ref->getPointeeType();
4733 // Is it a non-const lvalue reference?
4734 if (!ArgType.isConstQualified())
4735 AcceptsConst = false;
4736 }
4737 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4738 continue;
4739
4740 // We have a single argument of type cv X or cv X&, i.e. we've found the
4741 // copy assignment operator. Return whether it accepts const arguments.
4742 return AcceptsConst;
4743 }
4744 assert(Class->isInvalidDecl() &&
4745 "No copy assignment operator declared in valid code.");
4746 return false;
4747}
4748
Douglas Gregor0be31a22010-07-02 17:43:08 +00004749CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004750 // Note: The following rules are largely analoguous to the copy
4751 // constructor rules. Note that virtual bases are not taken into account
4752 // for determining the argument type of the operator. Note also that
4753 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004754
4755
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004756 // C++ [class.copy]p10:
4757 // If the class definition does not explicitly declare a copy
4758 // assignment operator, one is declared implicitly.
4759 // The implicitly-defined copy assignment operator for a class X
4760 // will have the form
4761 //
4762 // X& X::operator=(const X&)
4763 //
4764 // if
4765 bool HasConstCopyAssignment = true;
4766
4767 // -- each direct base class B of X has a copy assignment operator
4768 // whose parameter is of type const B&, const volatile B& or B,
4769 // and
4770 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4771 BaseEnd = ClassDecl->bases_end();
4772 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4773 assert(!Base->getType()->isDependentType() &&
4774 "Cannot generate implicit members for class with dependent bases.");
4775 const CXXRecordDecl *BaseClassDecl
4776 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004777 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004778 }
4779
4780 // -- for all the nonstatic data members of X that are of a class
4781 // type M (or array thereof), each such class type has a copy
4782 // assignment operator whose parameter is of type const M&,
4783 // const volatile M& or M.
4784 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4785 FieldEnd = ClassDecl->field_end();
4786 HasConstCopyAssignment && Field != FieldEnd;
4787 ++Field) {
4788 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4789 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4790 const CXXRecordDecl *FieldClassDecl
4791 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004792 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004793 }
4794 }
4795
4796 // Otherwise, the implicitly declared copy assignment operator will
4797 // have the form
4798 //
4799 // X& X::operator=(X&)
4800 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4801 QualType RetType = Context.getLValueReferenceType(ArgType);
4802 if (HasConstCopyAssignment)
4803 ArgType = ArgType.withConst();
4804 ArgType = Context.getLValueReferenceType(ArgType);
4805
Douglas Gregor68e11362010-07-01 17:48:08 +00004806 // C++ [except.spec]p14:
4807 // An implicitly declared special member function (Clause 12) shall have an
4808 // exception-specification. [...]
4809 ImplicitExceptionSpecification ExceptSpec(Context);
4810 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4811 BaseEnd = ClassDecl->bases_end();
4812 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004813 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004814 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004815
4816 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4817 DeclareImplicitCopyAssignment(BaseClassDecl);
4818
Douglas Gregor68e11362010-07-01 17:48:08 +00004819 if (CXXMethodDecl *CopyAssign
4820 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4821 ExceptSpec.CalledDecl(CopyAssign);
4822 }
4823 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4824 FieldEnd = ClassDecl->field_end();
4825 Field != FieldEnd;
4826 ++Field) {
4827 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4828 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004829 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004830 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004831
4832 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4833 DeclareImplicitCopyAssignment(FieldClassDecl);
4834
Douglas Gregor68e11362010-07-01 17:48:08 +00004835 if (CXXMethodDecl *CopyAssign
4836 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4837 ExceptSpec.CalledDecl(CopyAssign);
4838 }
4839 }
4840
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004841 // An implicitly-declared copy assignment operator is an inline public
4842 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004843 FunctionProtoType::ExtProtoInfo EPI;
4844 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4845 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4846 EPI.NumExceptions = ExceptSpec.size();
4847 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004848 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004849 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004850 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004851 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004852 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004853 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004854 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004855 /*isInline=*/true);
4856 CopyAssignment->setAccess(AS_public);
4857 CopyAssignment->setImplicit();
4858 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004859
4860 // Add the parameter to the operator.
4861 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4862 ClassDecl->getLocation(),
4863 /*Id=*/0,
4864 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004865 SC_None,
4866 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004867 CopyAssignment->setParams(&FromParam, 1);
4868
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004869 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004870 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4871
Douglas Gregor0be31a22010-07-02 17:43:08 +00004872 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004873 PushOnScopeChains(CopyAssignment, S, false);
4874 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004875
4876 AddOverriddenMethods(ClassDecl, CopyAssignment);
4877 return CopyAssignment;
4878}
4879
Douglas Gregorb139cd52010-05-01 20:49:11 +00004880void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4881 CXXMethodDecl *CopyAssignOperator) {
4882 assert((CopyAssignOperator->isImplicit() &&
4883 CopyAssignOperator->isOverloadedOperator() &&
4884 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004885 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004886 "DefineImplicitCopyAssignment called for wrong function");
4887
4888 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4889
4890 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4891 CopyAssignOperator->setInvalidDecl();
4892 return;
4893 }
4894
4895 CopyAssignOperator->setUsed();
4896
4897 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004898 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004899
4900 // C++0x [class.copy]p30:
4901 // The implicitly-defined or explicitly-defaulted copy assignment operator
4902 // for a non-union class X performs memberwise copy assignment of its
4903 // subobjects. The direct base classes of X are assigned first, in the
4904 // order of their declaration in the base-specifier-list, and then the
4905 // immediate non-static data members of X are assigned, in the order in
4906 // which they were declared in the class definition.
4907
4908 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004909 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004910
4911 // The parameter for the "other" object, which we are copying from.
4912 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4913 Qualifiers OtherQuals = Other->getType().getQualifiers();
4914 QualType OtherRefType = Other->getType();
4915 if (const LValueReferenceType *OtherRef
4916 = OtherRefType->getAs<LValueReferenceType>()) {
4917 OtherRefType = OtherRef->getPointeeType();
4918 OtherQuals = OtherRefType.getQualifiers();
4919 }
4920
4921 // Our location for everything implicitly-generated.
4922 SourceLocation Loc = CopyAssignOperator->getLocation();
4923
4924 // Construct a reference to the "other" object. We'll be using this
4925 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00004926 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004927 assert(OtherRef && "Reference to parameter cannot fail!");
4928
4929 // Construct the "this" pointer. We'll be using this throughout the generated
4930 // ASTs.
4931 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4932 assert(This && "Reference to this cannot fail!");
4933
4934 // Assign base classes.
4935 bool Invalid = false;
4936 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4937 E = ClassDecl->bases_end(); Base != E; ++Base) {
4938 // Form the assignment:
4939 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4940 QualType BaseType = Base->getType().getUnqualifiedType();
4941 CXXRecordDecl *BaseClassDecl = 0;
4942 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4943 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4944 else {
4945 Invalid = true;
4946 continue;
4947 }
4948
John McCallcf142162010-08-07 06:22:56 +00004949 CXXCastPath BasePath;
4950 BasePath.push_back(Base);
4951
Douglas Gregorb139cd52010-05-01 20:49:11 +00004952 // Construct the "from" expression, which is an implicit cast to the
4953 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00004954 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004955 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004956 CK_UncheckedDerivedToBase,
4957 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004958
4959 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004960 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004961
4962 // Implicitly cast "this" to the appropriately-qualified base type.
4963 Expr *ToE = To.takeAs<Expr>();
4964 ImpCastExprToType(ToE,
4965 Context.getCVRQualifiedType(BaseType,
4966 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004967 CK_UncheckedDerivedToBase,
4968 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004969 To = Owned(ToE);
4970
4971 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004972 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004973 To.get(), From,
4974 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004975 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004976 Diag(CurrentLocation, diag::note_member_synthesized_at)
4977 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4978 CopyAssignOperator->setInvalidDecl();
4979 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004980 }
4981
4982 // Success! Record the copy.
4983 Statements.push_back(Copy.takeAs<Expr>());
4984 }
4985
4986 // \brief Reference to the __builtin_memcpy function.
4987 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004988 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004989 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004990
4991 // Assign non-static members.
4992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4993 FieldEnd = ClassDecl->field_end();
4994 Field != FieldEnd; ++Field) {
4995 // Check for members of reference type; we can't copy those.
4996 if (Field->getType()->isReferenceType()) {
4997 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4998 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4999 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005000 Diag(CurrentLocation, diag::note_member_synthesized_at)
5001 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005002 Invalid = true;
5003 continue;
5004 }
5005
5006 // Check for members of const-qualified, non-class type.
5007 QualType BaseType = Context.getBaseElementType(Field->getType());
5008 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5009 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5010 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5011 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005012 Diag(CurrentLocation, diag::note_member_synthesized_at)
5013 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005014 Invalid = true;
5015 continue;
5016 }
5017
5018 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005019 if (FieldType->isIncompleteArrayType()) {
5020 assert(ClassDecl->hasFlexibleArrayMember() &&
5021 "Incomplete array type is not valid");
5022 continue;
5023 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005024
5025 // Build references to the field in the object we're copying from and to.
5026 CXXScopeSpec SS; // Intentionally empty
5027 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5028 LookupMemberName);
5029 MemberLookup.addDecl(*Field);
5030 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005031 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005032 Loc, /*IsArrow=*/false,
5033 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005034 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005035 Loc, /*IsArrow=*/true,
5036 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005037 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5038 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5039
5040 // If the field should be copied with __builtin_memcpy rather than via
5041 // explicit assignments, do so. This optimization only applies for arrays
5042 // of scalars and arrays of class type with trivial copy-assignment
5043 // operators.
5044 if (FieldType->isArrayType() &&
5045 (!BaseType->isRecordType() ||
5046 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5047 ->hasTrivialCopyAssignment())) {
5048 // Compute the size of the memory buffer to be copied.
5049 QualType SizeType = Context.getSizeType();
5050 llvm::APInt Size(Context.getTypeSize(SizeType),
5051 Context.getTypeSizeInChars(BaseType).getQuantity());
5052 for (const ConstantArrayType *Array
5053 = Context.getAsConstantArrayType(FieldType);
5054 Array;
5055 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005056 llvm::APInt ArraySize
5057 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005058 Size *= ArraySize;
5059 }
5060
5061 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005062 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5063 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005064
5065 bool NeedsCollectableMemCpy =
5066 (BaseType->isRecordType() &&
5067 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5068
5069 if (NeedsCollectableMemCpy) {
5070 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005071 // Create a reference to the __builtin_objc_memmove_collectable function.
5072 LookupResult R(*this,
5073 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005074 Loc, LookupOrdinaryName);
5075 LookupName(R, TUScope, true);
5076
5077 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5078 if (!CollectableMemCpy) {
5079 // Something went horribly wrong earlier, and we will have
5080 // complained about it.
5081 Invalid = true;
5082 continue;
5083 }
5084
5085 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5086 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005087 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005088 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5089 }
5090 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005091 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005092 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005093 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5094 LookupOrdinaryName);
5095 LookupName(R, TUScope, true);
5096
5097 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5098 if (!BuiltinMemCpy) {
5099 // Something went horribly wrong earlier, and we will have complained
5100 // about it.
5101 Invalid = true;
5102 continue;
5103 }
5104
5105 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5106 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005107 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005108 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5109 }
5110
John McCall37ad5512010-08-23 06:44:23 +00005111 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005112 CallArgs.push_back(To.takeAs<Expr>());
5113 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005114 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005115 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005116 if (NeedsCollectableMemCpy)
5117 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005118 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005119 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005120 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005121 else
5122 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005123 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005124 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005125 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005126
Douglas Gregorb139cd52010-05-01 20:49:11 +00005127 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5128 Statements.push_back(Call.takeAs<Expr>());
5129 continue;
5130 }
5131
5132 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005133 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005134 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005135 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005136 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005137 Diag(CurrentLocation, diag::note_member_synthesized_at)
5138 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5139 CopyAssignOperator->setInvalidDecl();
5140 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005141 }
5142
5143 // Success! Record the copy.
5144 Statements.push_back(Copy.takeAs<Stmt>());
5145 }
5146
5147 if (!Invalid) {
5148 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005149 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005150
John McCalldadc5752010-08-24 06:29:42 +00005151 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005152 if (Return.isInvalid())
5153 Invalid = true;
5154 else {
5155 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005156
5157 if (Trap.hasErrorOccurred()) {
5158 Diag(CurrentLocation, diag::note_member_synthesized_at)
5159 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5160 Invalid = true;
5161 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005162 }
5163 }
5164
5165 if (Invalid) {
5166 CopyAssignOperator->setInvalidDecl();
5167 return;
5168 }
5169
John McCalldadc5752010-08-24 06:29:42 +00005170 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005171 /*isStmtExpr=*/false);
5172 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5173 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005174}
5175
Douglas Gregor0be31a22010-07-02 17:43:08 +00005176CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5177 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005178 // C++ [class.copy]p4:
5179 // If the class definition does not explicitly declare a copy
5180 // constructor, one is declared implicitly.
5181
Douglas Gregor54be3392010-07-01 17:57:27 +00005182 // C++ [class.copy]p5:
5183 // The implicitly-declared copy constructor for a class X will
5184 // have the form
5185 //
5186 // X::X(const X&)
5187 //
5188 // if
5189 bool HasConstCopyConstructor = true;
5190
5191 // -- each direct or virtual base class B of X has a copy
5192 // constructor whose first parameter is of type const B& or
5193 // const volatile B&, and
5194 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5195 BaseEnd = ClassDecl->bases_end();
5196 HasConstCopyConstructor && Base != BaseEnd;
5197 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005198 // Virtual bases are handled below.
5199 if (Base->isVirtual())
5200 continue;
5201
Douglas Gregora6d69502010-07-02 23:41:54 +00005202 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005203 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005204 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5205 DeclareImplicitCopyConstructor(BaseClassDecl);
5206
Douglas Gregorcfe68222010-07-01 18:27:03 +00005207 HasConstCopyConstructor
5208 = BaseClassDecl->hasConstCopyConstructor(Context);
5209 }
5210
5211 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5212 BaseEnd = ClassDecl->vbases_end();
5213 HasConstCopyConstructor && Base != BaseEnd;
5214 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005215 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005216 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005217 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5218 DeclareImplicitCopyConstructor(BaseClassDecl);
5219
Douglas Gregor54be3392010-07-01 17:57:27 +00005220 HasConstCopyConstructor
5221 = BaseClassDecl->hasConstCopyConstructor(Context);
5222 }
5223
5224 // -- for all the nonstatic data members of X that are of a
5225 // class type M (or array thereof), each such class type
5226 // has a copy constructor whose first parameter is of type
5227 // const M& or const volatile M&.
5228 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5229 FieldEnd = ClassDecl->field_end();
5230 HasConstCopyConstructor && Field != FieldEnd;
5231 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005232 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005233 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005234 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005235 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005236 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5237 DeclareImplicitCopyConstructor(FieldClassDecl);
5238
Douglas Gregor54be3392010-07-01 17:57:27 +00005239 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005240 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005241 }
5242 }
5243
5244 // Otherwise, the implicitly declared copy constructor will have
5245 // the form
5246 //
5247 // X::X(X&)
5248 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5249 QualType ArgType = ClassType;
5250 if (HasConstCopyConstructor)
5251 ArgType = ArgType.withConst();
5252 ArgType = Context.getLValueReferenceType(ArgType);
5253
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005254 // C++ [except.spec]p14:
5255 // An implicitly declared special member function (Clause 12) shall have an
5256 // exception-specification. [...]
5257 ImplicitExceptionSpecification ExceptSpec(Context);
5258 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5259 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5260 BaseEnd = ClassDecl->bases_end();
5261 Base != BaseEnd;
5262 ++Base) {
5263 // Virtual bases are handled below.
5264 if (Base->isVirtual())
5265 continue;
5266
Douglas Gregora6d69502010-07-02 23:41:54 +00005267 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005268 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005269 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5270 DeclareImplicitCopyConstructor(BaseClassDecl);
5271
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005272 if (CXXConstructorDecl *CopyConstructor
5273 = BaseClassDecl->getCopyConstructor(Context, Quals))
5274 ExceptSpec.CalledDecl(CopyConstructor);
5275 }
5276 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5277 BaseEnd = ClassDecl->vbases_end();
5278 Base != BaseEnd;
5279 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005280 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005281 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005282 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5283 DeclareImplicitCopyConstructor(BaseClassDecl);
5284
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005285 if (CXXConstructorDecl *CopyConstructor
5286 = BaseClassDecl->getCopyConstructor(Context, Quals))
5287 ExceptSpec.CalledDecl(CopyConstructor);
5288 }
5289 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5290 FieldEnd = ClassDecl->field_end();
5291 Field != FieldEnd;
5292 ++Field) {
5293 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5294 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005295 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005296 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005297 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5298 DeclareImplicitCopyConstructor(FieldClassDecl);
5299
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005300 if (CXXConstructorDecl *CopyConstructor
5301 = FieldClassDecl->getCopyConstructor(Context, Quals))
5302 ExceptSpec.CalledDecl(CopyConstructor);
5303 }
5304 }
5305
Douglas Gregor54be3392010-07-01 17:57:27 +00005306 // An implicitly-declared copy constructor is an inline public
5307 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005308 FunctionProtoType::ExtProtoInfo EPI;
5309 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5310 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5311 EPI.NumExceptions = ExceptSpec.size();
5312 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005313 DeclarationName Name
5314 = Context.DeclarationNames.getCXXConstructorName(
5315 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005316 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005317 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005318 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005319 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005320 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005321 /*TInfo=*/0,
5322 /*isExplicit=*/false,
5323 /*isInline=*/true,
5324 /*isImplicitlyDeclared=*/true);
5325 CopyConstructor->setAccess(AS_public);
5326 CopyConstructor->setImplicit();
5327 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5328
Douglas Gregora6d69502010-07-02 23:41:54 +00005329 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005330 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5331
Douglas Gregor54be3392010-07-01 17:57:27 +00005332 // Add the parameter to the constructor.
5333 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5334 ClassDecl->getLocation(),
5335 /*IdentifierInfo=*/0,
5336 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005337 SC_None,
5338 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005339 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005340 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005341 PushOnScopeChains(CopyConstructor, S, false);
5342 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005343
5344 return CopyConstructor;
5345}
5346
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005347void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5348 CXXConstructorDecl *CopyConstructor,
5349 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005350 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005351 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005352 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005353 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005354
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005355 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005356 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005357
Douglas Gregora57478e2010-05-01 15:04:51 +00005358 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005359 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005360
Douglas Gregor54818f02010-05-12 16:39:35 +00005361 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5362 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005363 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005364 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005365 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005366 } else {
5367 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5368 CopyConstructor->getLocation(),
5369 MultiStmtArg(*this, 0, 0),
5370 /*isStmtExpr=*/false)
5371 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005372 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005373
5374 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005375}
5376
John McCalldadc5752010-08-24 06:29:42 +00005377ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005378Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005379 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005380 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005381 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005382 unsigned ConstructKind,
5383 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005384 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005385
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005386 // C++0x [class.copy]p34:
5387 // When certain criteria are met, an implementation is allowed to
5388 // omit the copy/move construction of a class object, even if the
5389 // copy/move constructor and/or destructor for the object have
5390 // side effects. [...]
5391 // - when a temporary class object that has not been bound to a
5392 // reference (12.2) would be copied/moved to a class object
5393 // with the same cv-unqualified type, the copy/move operation
5394 // can be omitted by constructing the temporary object
5395 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005396 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5397 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005398 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005399 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005400 }
Mike Stump11289f42009-09-09 15:08:12 +00005401
5402 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005403 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005404 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005405}
5406
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005407/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5408/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005409ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005410Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5411 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005412 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005413 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005414 unsigned ConstructKind,
5415 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005416 unsigned NumExprs = ExprArgs.size();
5417 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005418
Douglas Gregor27381f32009-11-23 12:27:39 +00005419 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005420 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005421 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005422 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005423 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5424 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005425}
5426
Mike Stump11289f42009-09-09 15:08:12 +00005427bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005428 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005429 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005430 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005431 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005432 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005433 move(Exprs), false, CXXConstructExpr::CK_Complete,
5434 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005435 if (TempResult.isInvalid())
5436 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005437
Anders Carlsson6eb55572009-08-25 05:12:04 +00005438 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005439 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005440 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005441 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005442 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005443
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005444 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005445}
5446
John McCall03c48482010-02-02 09:10:11 +00005447void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5448 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005449 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005450 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005451 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005452 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005453 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005454 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005455 << VD->getDeclName()
5456 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005457
John McCall386dfc72010-09-18 05:25:11 +00005458 // TODO: this should be re-enabled for static locals by !CXAAtExit
5459 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005460 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005461 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005462}
5463
Mike Stump11289f42009-09-09 15:08:12 +00005464/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005465/// ActOnDeclarator, when a C++ direct initializer is present.
5466/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005467void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005468 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005469 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005470 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005471 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005472
5473 // If there is no declaration, there was an error parsing it. Just ignore
5474 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005475 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005476 return;
Mike Stump11289f42009-09-09 15:08:12 +00005477
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005478 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5479 if (!VDecl) {
5480 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5481 RealDecl->setInvalidDecl();
5482 return;
5483 }
5484
Douglas Gregor402250f2009-08-26 21:14:46 +00005485 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005486 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005487 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5488 //
5489 // Clients that want to distinguish between the two forms, can check for
5490 // direct initializer using VarDecl::hasCXXDirectInitializer().
5491 // A major benefit is that clients that don't particularly care about which
5492 // exactly form was it (like the CodeGen) can handle both cases without
5493 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005494
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005495 // C++ 8.5p11:
5496 // The form of initialization (using parentheses or '=') is generally
5497 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005498 // class type.
5499
Douglas Gregor50dc2192010-02-11 22:55:30 +00005500 if (!VDecl->getType()->isDependentType() &&
5501 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005502 diag::err_typecheck_decl_incomplete_type)) {
5503 VDecl->setInvalidDecl();
5504 return;
5505 }
5506
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005507 // The variable can not have an abstract class type.
5508 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5509 diag::err_abstract_type_in_decl,
5510 AbstractVariableType))
5511 VDecl->setInvalidDecl();
5512
Sebastian Redl5ca79842010-02-01 20:16:42 +00005513 const VarDecl *Def;
5514 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005515 Diag(VDecl->getLocation(), diag::err_redefinition)
5516 << VDecl->getDeclName();
5517 Diag(Def->getLocation(), diag::note_previous_definition);
5518 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005519 return;
5520 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005521
Douglas Gregorf0f83692010-08-24 05:27:49 +00005522 // C++ [class.static.data]p4
5523 // If a static data member is of const integral or const
5524 // enumeration type, its declaration in the class definition can
5525 // specify a constant-initializer which shall be an integral
5526 // constant expression (5.19). In that case, the member can appear
5527 // in integral constant expressions. The member shall still be
5528 // defined in a namespace scope if it is used in the program and the
5529 // namespace scope definition shall not contain an initializer.
5530 //
5531 // We already performed a redefinition check above, but for static
5532 // data members we also need to check whether there was an in-class
5533 // declaration with an initializer.
5534 const VarDecl* PrevInit = 0;
5535 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5536 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5537 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5538 return;
5539 }
5540
Douglas Gregor71f39c92010-12-16 01:31:22 +00005541 bool IsDependent = false;
5542 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5543 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5544 VDecl->setInvalidDecl();
5545 return;
5546 }
5547
5548 if (Exprs.get()[I]->isTypeDependent())
5549 IsDependent = true;
5550 }
5551
Douglas Gregor50dc2192010-02-11 22:55:30 +00005552 // If either the declaration has a dependent type or if any of the
5553 // expressions is type-dependent, we represent the initialization
5554 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005555 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005556 // Let clients know that initialization was done with a direct initializer.
5557 VDecl->setCXXDirectInitializer(true);
5558
5559 // Store the initialization expressions as a ParenListExpr.
5560 unsigned NumExprs = Exprs.size();
5561 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5562 (Expr **)Exprs.release(),
5563 NumExprs, RParenLoc));
5564 return;
5565 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005566
5567 // Capture the variable that is being initialized and the style of
5568 // initialization.
5569 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5570
5571 // FIXME: Poor source location information.
5572 InitializationKind Kind
5573 = InitializationKind::CreateDirect(VDecl->getLocation(),
5574 LParenLoc, RParenLoc);
5575
5576 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005577 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005578 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005579 if (Result.isInvalid()) {
5580 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005581 return;
5582 }
John McCallacf0ee52010-10-08 02:01:28 +00005583
5584 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005585
Douglas Gregora40433a2010-12-07 00:41:46 +00005586 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005587 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005588 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005589
John McCall8b0f4ff2010-08-02 21:13:48 +00005590 if (!VDecl->isInvalidDecl() &&
5591 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005592 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005593 !VDecl->getInit()->isConstantInitializer(Context,
5594 VDecl->getType()->isReferenceType()))
5595 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5596 << VDecl->getInit()->getSourceRange();
5597
John McCall03c48482010-02-02 09:10:11 +00005598 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5599 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005600}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005601
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005602/// \brief Given a constructor and the set of arguments provided for the
5603/// constructor, convert the arguments and add any required default arguments
5604/// to form a proper call to this constructor.
5605///
5606/// \returns true if an error occurred, false otherwise.
5607bool
5608Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5609 MultiExprArg ArgsPtr,
5610 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005611 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005612 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5613 unsigned NumArgs = ArgsPtr.size();
5614 Expr **Args = (Expr **)ArgsPtr.get();
5615
5616 const FunctionProtoType *Proto
5617 = Constructor->getType()->getAs<FunctionProtoType>();
5618 assert(Proto && "Constructor without a prototype?");
5619 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005620
5621 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005622 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005623 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005624 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005625 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005626
5627 VariadicCallType CallType =
5628 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5629 llvm::SmallVector<Expr *, 8> AllArgs;
5630 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5631 Proto, 0, Args, NumArgs, AllArgs,
5632 CallType);
5633 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5634 ConvertedArgs.push_back(AllArgs[i]);
5635 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005636}
5637
Anders Carlssone363c8e2009-12-12 00:32:00 +00005638static inline bool
5639CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5640 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005641 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005642 if (isa<NamespaceDecl>(DC)) {
5643 return SemaRef.Diag(FnDecl->getLocation(),
5644 diag::err_operator_new_delete_declared_in_namespace)
5645 << FnDecl->getDeclName();
5646 }
5647
5648 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005649 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005650 return SemaRef.Diag(FnDecl->getLocation(),
5651 diag::err_operator_new_delete_declared_static)
5652 << FnDecl->getDeclName();
5653 }
5654
Anders Carlsson60659a82009-12-12 02:43:16 +00005655 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005656}
5657
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005658static inline bool
5659CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5660 CanQualType ExpectedResultType,
5661 CanQualType ExpectedFirstParamType,
5662 unsigned DependentParamTypeDiag,
5663 unsigned InvalidParamTypeDiag) {
5664 QualType ResultType =
5665 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5666
5667 // Check that the result type is not dependent.
5668 if (ResultType->isDependentType())
5669 return SemaRef.Diag(FnDecl->getLocation(),
5670 diag::err_operator_new_delete_dependent_result_type)
5671 << FnDecl->getDeclName() << ExpectedResultType;
5672
5673 // Check that the result type is what we expect.
5674 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5675 return SemaRef.Diag(FnDecl->getLocation(),
5676 diag::err_operator_new_delete_invalid_result_type)
5677 << FnDecl->getDeclName() << ExpectedResultType;
5678
5679 // A function template must have at least 2 parameters.
5680 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5681 return SemaRef.Diag(FnDecl->getLocation(),
5682 diag::err_operator_new_delete_template_too_few_parameters)
5683 << FnDecl->getDeclName();
5684
5685 // The function decl must have at least 1 parameter.
5686 if (FnDecl->getNumParams() == 0)
5687 return SemaRef.Diag(FnDecl->getLocation(),
5688 diag::err_operator_new_delete_too_few_parameters)
5689 << FnDecl->getDeclName();
5690
5691 // Check the the first parameter type is not dependent.
5692 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5693 if (FirstParamType->isDependentType())
5694 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5695 << FnDecl->getDeclName() << ExpectedFirstParamType;
5696
5697 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005698 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005699 ExpectedFirstParamType)
5700 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5701 << FnDecl->getDeclName() << ExpectedFirstParamType;
5702
5703 return false;
5704}
5705
Anders Carlsson12308f42009-12-11 23:23:22 +00005706static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005707CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005708 // C++ [basic.stc.dynamic.allocation]p1:
5709 // A program is ill-formed if an allocation function is declared in a
5710 // namespace scope other than global scope or declared static in global
5711 // scope.
5712 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5713 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005714
5715 CanQualType SizeTy =
5716 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5717
5718 // C++ [basic.stc.dynamic.allocation]p1:
5719 // The return type shall be void*. The first parameter shall have type
5720 // std::size_t.
5721 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5722 SizeTy,
5723 diag::err_operator_new_dependent_param_type,
5724 diag::err_operator_new_param_type))
5725 return true;
5726
5727 // C++ [basic.stc.dynamic.allocation]p1:
5728 // The first parameter shall not have an associated default argument.
5729 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005730 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005731 diag::err_operator_new_default_arg)
5732 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5733
5734 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005735}
5736
5737static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005738CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5739 // C++ [basic.stc.dynamic.deallocation]p1:
5740 // A program is ill-formed if deallocation functions are declared in a
5741 // namespace scope other than global scope or declared static in global
5742 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005743 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5744 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005745
5746 // C++ [basic.stc.dynamic.deallocation]p2:
5747 // Each deallocation function shall return void and its first parameter
5748 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005749 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5750 SemaRef.Context.VoidPtrTy,
5751 diag::err_operator_delete_dependent_param_type,
5752 diag::err_operator_delete_param_type))
5753 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005754
Anders Carlsson12308f42009-12-11 23:23:22 +00005755 return false;
5756}
5757
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005758/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5759/// of this overloaded operator is well-formed. If so, returns false;
5760/// otherwise, emits appropriate diagnostics and returns true.
5761bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005762 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005763 "Expected an overloaded operator declaration");
5764
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005765 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5766
Mike Stump11289f42009-09-09 15:08:12 +00005767 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005768 // The allocation and deallocation functions, operator new,
5769 // operator new[], operator delete and operator delete[], are
5770 // described completely in 3.7.3. The attributes and restrictions
5771 // found in the rest of this subclause do not apply to them unless
5772 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005773 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005774 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005775
Anders Carlsson22f443f2009-12-12 00:26:23 +00005776 if (Op == OO_New || Op == OO_Array_New)
5777 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005778
5779 // C++ [over.oper]p6:
5780 // An operator function shall either be a non-static member
5781 // function or be a non-member function and have at least one
5782 // parameter whose type is a class, a reference to a class, an
5783 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005784 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5785 if (MethodDecl->isStatic())
5786 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005787 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005788 } else {
5789 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005790 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5791 ParamEnd = FnDecl->param_end();
5792 Param != ParamEnd; ++Param) {
5793 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005794 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5795 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005796 ClassOrEnumParam = true;
5797 break;
5798 }
5799 }
5800
Douglas Gregord69246b2008-11-17 16:14:12 +00005801 if (!ClassOrEnumParam)
5802 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005803 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005804 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005805 }
5806
5807 // C++ [over.oper]p8:
5808 // An operator function cannot have default arguments (8.3.6),
5809 // except where explicitly stated below.
5810 //
Mike Stump11289f42009-09-09 15:08:12 +00005811 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005812 // (C++ [over.call]p1).
5813 if (Op != OO_Call) {
5814 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5815 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005816 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005817 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005818 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005819 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005820 }
5821 }
5822
Douglas Gregor6cf08062008-11-10 13:38:07 +00005823 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5824 { false, false, false }
5825#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5826 , { Unary, Binary, MemberOnly }
5827#include "clang/Basic/OperatorKinds.def"
5828 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005829
Douglas Gregor6cf08062008-11-10 13:38:07 +00005830 bool CanBeUnaryOperator = OperatorUses[Op][0];
5831 bool CanBeBinaryOperator = OperatorUses[Op][1];
5832 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005833
5834 // C++ [over.oper]p8:
5835 // [...] Operator functions cannot have more or fewer parameters
5836 // than the number required for the corresponding operator, as
5837 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005838 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005839 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005840 if (Op != OO_Call &&
5841 ((NumParams == 1 && !CanBeUnaryOperator) ||
5842 (NumParams == 2 && !CanBeBinaryOperator) ||
5843 (NumParams < 1) || (NumParams > 2))) {
5844 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005845 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005846 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005847 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005848 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005849 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005850 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005851 assert(CanBeBinaryOperator &&
5852 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005853 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005854 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005855
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005856 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005857 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005858 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005859
Douglas Gregord69246b2008-11-17 16:14:12 +00005860 // Overloaded operators other than operator() cannot be variadic.
5861 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005862 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005863 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005864 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005865 }
5866
5867 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005868 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5869 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005870 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005871 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005872 }
5873
5874 // C++ [over.inc]p1:
5875 // The user-defined function called operator++ implements the
5876 // prefix and postfix ++ operator. If this function is a member
5877 // function with no parameters, or a non-member function with one
5878 // parameter of class or enumeration type, it defines the prefix
5879 // increment operator ++ for objects of that type. If the function
5880 // is a member function with one parameter (which shall be of type
5881 // int) or a non-member function with two parameters (the second
5882 // of which shall be of type int), it defines the postfix
5883 // increment operator ++ for objects of that type.
5884 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5885 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5886 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005887 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005888 ParamIsInt = BT->getKind() == BuiltinType::Int;
5889
Chris Lattner2b786902008-11-21 07:50:02 +00005890 if (!ParamIsInt)
5891 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005892 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005893 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005894 }
5895
Douglas Gregord69246b2008-11-17 16:14:12 +00005896 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005897}
Chris Lattner3b024a32008-12-17 07:09:26 +00005898
Alexis Huntc88db062010-01-13 09:01:02 +00005899/// CheckLiteralOperatorDeclaration - Check whether the declaration
5900/// of this literal operator function is well-formed. If so, returns
5901/// false; otherwise, emits appropriate diagnostics and returns true.
5902bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5903 DeclContext *DC = FnDecl->getDeclContext();
5904 Decl::Kind Kind = DC->getDeclKind();
5905 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5906 Kind != Decl::LinkageSpec) {
5907 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5908 << FnDecl->getDeclName();
5909 return true;
5910 }
5911
5912 bool Valid = false;
5913
Alexis Hunt7dd26172010-04-07 23:11:06 +00005914 // template <char...> type operator "" name() is the only valid template
5915 // signature, and the only valid signature with no parameters.
5916 if (FnDecl->param_size() == 0) {
5917 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5918 // Must have only one template parameter
5919 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5920 if (Params->size() == 1) {
5921 NonTypeTemplateParmDecl *PmDecl =
5922 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005923
Alexis Hunt7dd26172010-04-07 23:11:06 +00005924 // The template parameter must be a char parameter pack.
5925 // FIXME: This test will always fail because non-type parameter packs
5926 // have not been implemented.
5927 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5928 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5929 Valid = true;
5930 }
5931 }
5932 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005933 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005934 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5935
Alexis Huntc88db062010-01-13 09:01:02 +00005936 QualType T = (*Param)->getType();
5937
Alexis Hunt079a6f72010-04-07 22:57:35 +00005938 // unsigned long long int, long double, and any character type are allowed
5939 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005940 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5941 Context.hasSameType(T, Context.LongDoubleTy) ||
5942 Context.hasSameType(T, Context.CharTy) ||
5943 Context.hasSameType(T, Context.WCharTy) ||
5944 Context.hasSameType(T, Context.Char16Ty) ||
5945 Context.hasSameType(T, Context.Char32Ty)) {
5946 if (++Param == FnDecl->param_end())
5947 Valid = true;
5948 goto FinishedParams;
5949 }
5950
Alexis Hunt079a6f72010-04-07 22:57:35 +00005951 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005952 const PointerType *PT = T->getAs<PointerType>();
5953 if (!PT)
5954 goto FinishedParams;
5955 T = PT->getPointeeType();
5956 if (!T.isConstQualified())
5957 goto FinishedParams;
5958 T = T.getUnqualifiedType();
5959
5960 // Move on to the second parameter;
5961 ++Param;
5962
5963 // If there is no second parameter, the first must be a const char *
5964 if (Param == FnDecl->param_end()) {
5965 if (Context.hasSameType(T, Context.CharTy))
5966 Valid = true;
5967 goto FinishedParams;
5968 }
5969
5970 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5971 // are allowed as the first parameter to a two-parameter function
5972 if (!(Context.hasSameType(T, Context.CharTy) ||
5973 Context.hasSameType(T, Context.WCharTy) ||
5974 Context.hasSameType(T, Context.Char16Ty) ||
5975 Context.hasSameType(T, Context.Char32Ty)))
5976 goto FinishedParams;
5977
5978 // The second and final parameter must be an std::size_t
5979 T = (*Param)->getType().getUnqualifiedType();
5980 if (Context.hasSameType(T, Context.getSizeType()) &&
5981 ++Param == FnDecl->param_end())
5982 Valid = true;
5983 }
5984
5985 // FIXME: This diagnostic is absolutely terrible.
5986FinishedParams:
5987 if (!Valid) {
5988 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5989 << FnDecl->getDeclName();
5990 return true;
5991 }
5992
5993 return false;
5994}
5995
Douglas Gregor07665a62009-01-05 19:45:36 +00005996/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5997/// linkage specification, including the language and (if present)
5998/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5999/// the location of the language string literal, which is provided
6000/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6001/// the '{' brace. Otherwise, this linkage specification does not
6002/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006003Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6004 SourceLocation LangLoc,
6005 llvm::StringRef Lang,
6006 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006007 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006008 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006009 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006010 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006011 Language = LinkageSpecDecl::lang_cxx;
6012 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006013 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006014 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006015 }
Mike Stump11289f42009-09-09 15:08:12 +00006016
Chris Lattner438e5012008-12-17 07:13:27 +00006017 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006018
Douglas Gregor07665a62009-01-05 19:45:36 +00006019 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006020 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006021 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006022 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006023 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006024 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006025}
6026
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006027/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006028/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6029/// valid, it's the position of the closing '}' brace in a linkage
6030/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006031Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6032 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006033 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006034 if (LinkageSpec)
6035 PopDeclContext();
6036 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006037}
6038
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006039/// \brief Perform semantic analysis for the variable declaration that
6040/// occurs within a C++ catch clause, returning the newly-created
6041/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006042VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006043 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006044 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006045 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006046 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006047 QualType ExDeclType = TInfo->getType();
6048
Sebastian Redl54c04d42008-12-22 19:15:10 +00006049 // Arrays and functions decay.
6050 if (ExDeclType->isArrayType())
6051 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6052 else if (ExDeclType->isFunctionType())
6053 ExDeclType = Context.getPointerType(ExDeclType);
6054
6055 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6056 // The exception-declaration shall not denote a pointer or reference to an
6057 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006058 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006059 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006060 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006061 Invalid = true;
6062 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006063
Douglas Gregor104ee002010-03-08 01:47:36 +00006064 // GCC allows catching pointers and references to incomplete types
6065 // as an extension; so do we, but we warn by default.
6066
Sebastian Redl54c04d42008-12-22 19:15:10 +00006067 QualType BaseType = ExDeclType;
6068 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006069 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006070 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006071 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006072 BaseType = Ptr->getPointeeType();
6073 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006074 DK = diag::ext_catch_incomplete_ptr;
6075 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006076 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006077 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006078 BaseType = Ref->getPointeeType();
6079 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006080 DK = diag::ext_catch_incomplete_ref;
6081 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006082 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006083 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006084 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6085 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006086 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006087
Mike Stump11289f42009-09-09 15:08:12 +00006088 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006089 RequireNonAbstractType(Loc, ExDeclType,
6090 diag::err_abstract_type_in_decl,
6091 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006092 Invalid = true;
6093
John McCall2ca705e2010-07-24 00:37:23 +00006094 // Only the non-fragile NeXT runtime currently supports C++ catches
6095 // of ObjC types, and no runtime supports catching ObjC types by value.
6096 if (!Invalid && getLangOptions().ObjC1) {
6097 QualType T = ExDeclType;
6098 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6099 T = RT->getPointeeType();
6100
6101 if (T->isObjCObjectType()) {
6102 Diag(Loc, diag::err_objc_object_catch);
6103 Invalid = true;
6104 } else if (T->isObjCObjectPointerType()) {
6105 if (!getLangOptions().NeXTRuntime) {
6106 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6107 Invalid = true;
6108 } else if (!getLangOptions().ObjCNonFragileABI) {
6109 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6110 Invalid = true;
6111 }
6112 }
6113 }
6114
Mike Stump11289f42009-09-09 15:08:12 +00006115 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006116 Name, ExDeclType, TInfo, SC_None,
6117 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006118 ExDecl->setExceptionVariable(true);
6119
Douglas Gregor6de584c2010-03-05 23:38:39 +00006120 if (!Invalid) {
6121 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6122 // C++ [except.handle]p16:
6123 // The object declared in an exception-declaration or, if the
6124 // exception-declaration does not specify a name, a temporary (12.2) is
6125 // copy-initialized (8.5) from the exception object. [...]
6126 // The object is destroyed when the handler exits, after the destruction
6127 // of any automatic objects initialized within the handler.
6128 //
6129 // We just pretend to initialize the object with itself, then make sure
6130 // it can be destroyed later.
6131 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6132 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006133 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006134 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6135 SourceLocation());
6136 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006137 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006138 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006139 if (Result.isInvalid())
6140 Invalid = true;
6141 else
6142 FinalizeVarWithDestructor(ExDecl, RecordTy);
6143 }
6144 }
6145
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006146 if (Invalid)
6147 ExDecl->setInvalidDecl();
6148
6149 return ExDecl;
6150}
6151
6152/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6153/// handler.
John McCall48871652010-08-21 09:40:31 +00006154Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006155 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006156 bool Invalid = D.isInvalidType();
6157
6158 // Check for unexpanded parameter packs.
6159 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6160 UPPC_ExceptionType)) {
6161 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6162 D.getIdentifierLoc());
6163 Invalid = true;
6164 }
6165
John McCall8cb7bdf2010-06-04 23:28:52 +00006166 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006167
Sebastian Redl54c04d42008-12-22 19:15:10 +00006168 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006169 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006170 LookupOrdinaryName,
6171 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006172 // The scope should be freshly made just for us. There is just no way
6173 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006174 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006175 if (PrevDecl->isTemplateParameter()) {
6176 // Maybe we will complain about the shadowed template parameter.
6177 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006178 }
6179 }
6180
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006181 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006182 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6183 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006184 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006185 }
6186
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006187 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006188 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006189 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006190
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006191 if (Invalid)
6192 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006193
Sebastian Redl54c04d42008-12-22 19:15:10 +00006194 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006195 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006196 PushOnScopeChains(ExDecl, S);
6197 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006198 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006199
Douglas Gregor758a8692009-06-17 21:51:59 +00006200 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006201 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006202}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006203
John McCall48871652010-08-21 09:40:31 +00006204Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006205 Expr *AssertExpr,
6206 Expr *AssertMessageExpr_) {
6207 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006208
Anders Carlsson54b26982009-03-14 00:33:21 +00006209 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6210 llvm::APSInt Value(32);
6211 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6212 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6213 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006214 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006215 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006216
Anders Carlsson54b26982009-03-14 00:33:21 +00006217 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006218 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006219 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006220 }
6221 }
Mike Stump11289f42009-09-09 15:08:12 +00006222
Douglas Gregoref68fee2010-12-15 23:55:21 +00006223 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6224 return 0;
6225
Mike Stump11289f42009-09-09 15:08:12 +00006226 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006227 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006228
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006229 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006230 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006231}
Sebastian Redlf769df52009-03-24 22:27:57 +00006232
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006233/// \brief Perform semantic analysis of the given friend type declaration.
6234///
6235/// \returns A friend declaration that.
6236FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6237 TypeSourceInfo *TSInfo) {
6238 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6239
6240 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006241 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006242
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006243 if (!getLangOptions().CPlusPlus0x) {
6244 // C++03 [class.friend]p2:
6245 // An elaborated-type-specifier shall be used in a friend declaration
6246 // for a class.*
6247 //
6248 // * The class-key of the elaborated-type-specifier is required.
6249 if (!ActiveTemplateInstantiations.empty()) {
6250 // Do not complain about the form of friend template types during
6251 // template instantiation; we will already have complained when the
6252 // template was declared.
6253 } else if (!T->isElaboratedTypeSpecifier()) {
6254 // If we evaluated the type to a record type, suggest putting
6255 // a tag in front.
6256 if (const RecordType *RT = T->getAs<RecordType>()) {
6257 RecordDecl *RD = RT->getDecl();
6258
6259 std::string InsertionText = std::string(" ") + RD->getKindName();
6260
6261 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6262 << (unsigned) RD->getTagKind()
6263 << T
6264 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6265 InsertionText);
6266 } else {
6267 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6268 << T
6269 << SourceRange(FriendLoc, TypeRange.getEnd());
6270 }
6271 } else if (T->getAs<EnumType>()) {
6272 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006273 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006274 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006275 }
6276 }
6277
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006278 // C++0x [class.friend]p3:
6279 // If the type specifier in a friend declaration designates a (possibly
6280 // cv-qualified) class type, that class is declared as a friend; otherwise,
6281 // the friend declaration is ignored.
6282
6283 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6284 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006285
6286 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6287}
6288
John McCallace48cd2010-10-19 01:40:49 +00006289/// Handle a friend tag declaration where the scope specifier was
6290/// templated.
6291Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6292 unsigned TagSpec, SourceLocation TagLoc,
6293 CXXScopeSpec &SS,
6294 IdentifierInfo *Name, SourceLocation NameLoc,
6295 AttributeList *Attr,
6296 MultiTemplateParamsArg TempParamLists) {
6297 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6298
6299 bool isExplicitSpecialization = false;
6300 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6301 bool Invalid = false;
6302
6303 if (TemplateParameterList *TemplateParams
6304 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6305 TempParamLists.get(),
6306 TempParamLists.size(),
6307 /*friend*/ true,
6308 isExplicitSpecialization,
6309 Invalid)) {
6310 --NumMatchedTemplateParamLists;
6311
6312 if (TemplateParams->size() > 0) {
6313 // This is a declaration of a class template.
6314 if (Invalid)
6315 return 0;
6316
6317 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6318 SS, Name, NameLoc, Attr,
6319 TemplateParams, AS_public).take();
6320 } else {
6321 // The "template<>" header is extraneous.
6322 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6323 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6324 isExplicitSpecialization = true;
6325 }
6326 }
6327
6328 if (Invalid) return 0;
6329
6330 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6331
6332 bool isAllExplicitSpecializations = true;
6333 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6334 if (TempParamLists.get()[I]->size()) {
6335 isAllExplicitSpecializations = false;
6336 break;
6337 }
6338 }
6339
6340 // FIXME: don't ignore attributes.
6341
6342 // If it's explicit specializations all the way down, just forget
6343 // about the template header and build an appropriate non-templated
6344 // friend. TODO: for source fidelity, remember the headers.
6345 if (isAllExplicitSpecializations) {
6346 ElaboratedTypeKeyword Keyword
6347 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6348 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6349 TagLoc, SS.getRange(), NameLoc);
6350 if (T.isNull())
6351 return 0;
6352
6353 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6354 if (isa<DependentNameType>(T)) {
6355 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6356 TL.setKeywordLoc(TagLoc);
6357 TL.setQualifierRange(SS.getRange());
6358 TL.setNameLoc(NameLoc);
6359 } else {
6360 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6361 TL.setKeywordLoc(TagLoc);
6362 TL.setQualifierRange(SS.getRange());
6363 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6364 }
6365
6366 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6367 TSI, FriendLoc);
6368 Friend->setAccess(AS_public);
6369 CurContext->addDecl(Friend);
6370 return Friend;
6371 }
6372
6373 // Handle the case of a templated-scope friend class. e.g.
6374 // template <class T> class A<T>::B;
6375 // FIXME: we don't support these right now.
6376 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6377 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6378 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6379 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6380 TL.setKeywordLoc(TagLoc);
6381 TL.setQualifierRange(SS.getRange());
6382 TL.setNameLoc(NameLoc);
6383
6384 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6385 TSI, FriendLoc);
6386 Friend->setAccess(AS_public);
6387 Friend->setUnsupportedFriend(true);
6388 CurContext->addDecl(Friend);
6389 return Friend;
6390}
6391
6392
John McCall11083da2009-09-16 22:47:08 +00006393/// Handle a friend type declaration. This works in tandem with
6394/// ActOnTag.
6395///
6396/// Notes on friend class templates:
6397///
6398/// We generally treat friend class declarations as if they were
6399/// declaring a class. So, for example, the elaborated type specifier
6400/// in a friend declaration is required to obey the restrictions of a
6401/// class-head (i.e. no typedefs in the scope chain), template
6402/// parameters are required to match up with simple template-ids, &c.
6403/// However, unlike when declaring a template specialization, it's
6404/// okay to refer to a template specialization without an empty
6405/// template parameter declaration, e.g.
6406/// friend class A<T>::B<unsigned>;
6407/// We permit this as a special case; if there are any template
6408/// parameters present at all, require proper matching, i.e.
6409/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006410Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006411 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006412 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006413
6414 assert(DS.isFriendSpecified());
6415 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6416
John McCall11083da2009-09-16 22:47:08 +00006417 // Try to convert the decl specifier to a type. This works for
6418 // friend templates because ActOnTag never produces a ClassTemplateDecl
6419 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006420 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006421 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6422 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006423 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006424 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006425
Douglas Gregor6c110f32010-12-16 01:14:37 +00006426 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6427 return 0;
6428
John McCall11083da2009-09-16 22:47:08 +00006429 // This is definitely an error in C++98. It's probably meant to
6430 // be forbidden in C++0x, too, but the specification is just
6431 // poorly written.
6432 //
6433 // The problem is with declarations like the following:
6434 // template <T> friend A<T>::foo;
6435 // where deciding whether a class C is a friend or not now hinges
6436 // on whether there exists an instantiation of A that causes
6437 // 'foo' to equal C. There are restrictions on class-heads
6438 // (which we declare (by fiat) elaborated friend declarations to
6439 // be) that makes this tractable.
6440 //
6441 // FIXME: handle "template <> friend class A<T>;", which
6442 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006443 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006444 Diag(Loc, diag::err_tagless_friend_type_template)
6445 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006446 return 0;
John McCall11083da2009-09-16 22:47:08 +00006447 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006448
John McCallaa74a0c2009-08-28 07:59:38 +00006449 // C++98 [class.friend]p1: A friend of a class is a function
6450 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006451 // This is fixed in DR77, which just barely didn't make the C++03
6452 // deadline. It's also a very silly restriction that seriously
6453 // affects inner classes and which nobody else seems to implement;
6454 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006455 //
6456 // But note that we could warn about it: it's always useless to
6457 // friend one of your own members (it's not, however, worthless to
6458 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006459
John McCall11083da2009-09-16 22:47:08 +00006460 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006461 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006462 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006463 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006464 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006465 TSI,
John McCall11083da2009-09-16 22:47:08 +00006466 DS.getFriendSpecLoc());
6467 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006468 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6469
6470 if (!D)
John McCall48871652010-08-21 09:40:31 +00006471 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006472
John McCall11083da2009-09-16 22:47:08 +00006473 D->setAccess(AS_public);
6474 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006475
John McCall48871652010-08-21 09:40:31 +00006476 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006477}
6478
John McCallde3fd222010-10-12 23:13:28 +00006479Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6480 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006481 const DeclSpec &DS = D.getDeclSpec();
6482
6483 assert(DS.isFriendSpecified());
6484 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6485
6486 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006487 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6488 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006489
6490 // C++ [class.friend]p1
6491 // A friend of a class is a function or class....
6492 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006493 // It *doesn't* see through dependent types, which is correct
6494 // according to [temp.arg.type]p3:
6495 // If a declaration acquires a function type through a
6496 // type dependent on a template-parameter and this causes
6497 // a declaration that does not use the syntactic form of a
6498 // function declarator to have a function type, the program
6499 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006500 if (!T->isFunctionType()) {
6501 Diag(Loc, diag::err_unexpected_friend);
6502
6503 // It might be worthwhile to try to recover by creating an
6504 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006505 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006506 }
6507
6508 // C++ [namespace.memdef]p3
6509 // - If a friend declaration in a non-local class first declares a
6510 // class or function, the friend class or function is a member
6511 // of the innermost enclosing namespace.
6512 // - The name of the friend is not found by simple name lookup
6513 // until a matching declaration is provided in that namespace
6514 // scope (either before or after the class declaration granting
6515 // friendship).
6516 // - If a friend function is called, its name may be found by the
6517 // name lookup that considers functions from namespaces and
6518 // classes associated with the types of the function arguments.
6519 // - When looking for a prior declaration of a class or a function
6520 // declared as a friend, scopes outside the innermost enclosing
6521 // namespace scope are not considered.
6522
John McCallde3fd222010-10-12 23:13:28 +00006523 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006524 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6525 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006526 assert(Name);
6527
Douglas Gregor6c110f32010-12-16 01:14:37 +00006528 // Check for unexpanded parameter packs.
6529 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6530 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6531 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6532 return 0;
6533
John McCall07e91c02009-08-06 02:15:43 +00006534 // The context we found the declaration in, or in which we should
6535 // create the declaration.
6536 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006537 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006538 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006539 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006540
John McCallde3fd222010-10-12 23:13:28 +00006541 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006542
John McCallde3fd222010-10-12 23:13:28 +00006543 // There are four cases here.
6544 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006545 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006546 // there as appropriate.
6547 // Recover from invalid scope qualifiers as if they just weren't there.
6548 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006549 // C++0x [namespace.memdef]p3:
6550 // If the name in a friend declaration is neither qualified nor
6551 // a template-id and the declaration is a function or an
6552 // elaborated-type-specifier, the lookup to determine whether
6553 // the entity has been previously declared shall not consider
6554 // any scopes outside the innermost enclosing namespace.
6555 // C++0x [class.friend]p11:
6556 // If a friend declaration appears in a local class and the name
6557 // specified is an unqualified name, a prior declaration is
6558 // looked up without considering scopes that are outside the
6559 // innermost enclosing non-class scope. For a friend function
6560 // declaration, if there is no prior declaration, the program is
6561 // ill-formed.
6562 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006563 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006564
John McCallf7cfb222010-10-13 05:45:15 +00006565 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006566 DC = CurContext;
6567 while (true) {
6568 // Skip class contexts. If someone can cite chapter and verse
6569 // for this behavior, that would be nice --- it's what GCC and
6570 // EDG do, and it seems like a reasonable intent, but the spec
6571 // really only says that checks for unqualified existing
6572 // declarations should stop at the nearest enclosing namespace,
6573 // not that they should only consider the nearest enclosing
6574 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006575 while (DC->isRecord())
6576 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006577
John McCall1f82f242009-11-18 22:49:29 +00006578 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006579
6580 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006581 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006582 break;
John McCallf7cfb222010-10-13 05:45:15 +00006583
John McCallf4776592010-10-14 22:22:28 +00006584 if (isTemplateId) {
6585 if (isa<TranslationUnitDecl>(DC)) break;
6586 } else {
6587 if (DC->isFileContext()) break;
6588 }
John McCall07e91c02009-08-06 02:15:43 +00006589 DC = DC->getParent();
6590 }
6591
6592 // C++ [class.friend]p1: A friend of a class is a function or
6593 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006594 // C++0x changes this for both friend types and functions.
6595 // Most C++ 98 compilers do seem to give an error here, so
6596 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006597 if (!Previous.empty() && DC->Equals(CurContext)
6598 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006599 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006600
John McCallccbc0322010-10-13 06:22:15 +00006601 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006602
John McCallde3fd222010-10-12 23:13:28 +00006603 // - There's a non-dependent scope specifier, in which case we
6604 // compute it and do a previous lookup there for a function
6605 // or function template.
6606 } else if (!SS.getScopeRep()->isDependent()) {
6607 DC = computeDeclContext(SS);
6608 if (!DC) return 0;
6609
6610 if (RequireCompleteDeclContext(SS, DC)) return 0;
6611
6612 LookupQualifiedName(Previous, DC);
6613
6614 // Ignore things found implicitly in the wrong scope.
6615 // TODO: better diagnostics for this case. Suggesting the right
6616 // qualified scope would be nice...
6617 LookupResult::Filter F = Previous.makeFilter();
6618 while (F.hasNext()) {
6619 NamedDecl *D = F.next();
6620 if (!DC->InEnclosingNamespaceSetOf(
6621 D->getDeclContext()->getRedeclContext()))
6622 F.erase();
6623 }
6624 F.done();
6625
6626 if (Previous.empty()) {
6627 D.setInvalidType();
6628 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6629 return 0;
6630 }
6631
6632 // C++ [class.friend]p1: A friend of a class is a function or
6633 // class that is not a member of the class . . .
6634 if (DC->Equals(CurContext))
6635 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6636
6637 // - There's a scope specifier that does not match any template
6638 // parameter lists, in which case we use some arbitrary context,
6639 // create a method or method template, and wait for instantiation.
6640 // - There's a scope specifier that does match some template
6641 // parameter lists, which we don't handle right now.
6642 } else {
6643 DC = CurContext;
6644 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006645 }
6646
John McCallf7cfb222010-10-13 05:45:15 +00006647 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006648 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006649 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6650 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6651 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006652 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006653 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6654 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006655 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006656 }
John McCall07e91c02009-08-06 02:15:43 +00006657 }
6658
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006659 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006660 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006661 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006662 IsDefinition,
6663 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006664 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006665
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006666 assert(ND->getDeclContext() == DC);
6667 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006668
John McCall759e32b2009-08-31 22:39:49 +00006669 // Add the function declaration to the appropriate lookup tables,
6670 // adjusting the redeclarations list as necessary. We don't
6671 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006672 //
John McCall759e32b2009-08-31 22:39:49 +00006673 // Also update the scope-based lookup if the target context's
6674 // lookup context is in lexical scope.
6675 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006676 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006677 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006678 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006679 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006680 }
John McCallaa74a0c2009-08-28 07:59:38 +00006681
6682 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006683 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006684 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006685 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006686 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006687
John McCallde3fd222010-10-12 23:13:28 +00006688 if (ND->isInvalidDecl())
6689 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006690 else {
6691 FunctionDecl *FD;
6692 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6693 FD = FTD->getTemplatedDecl();
6694 else
6695 FD = cast<FunctionDecl>(ND);
6696
6697 // Mark templated-scope function declarations as unsupported.
6698 if (FD->getNumTemplateParameterLists())
6699 FrD->setUnsupportedFriend(true);
6700 }
John McCallde3fd222010-10-12 23:13:28 +00006701
John McCall48871652010-08-21 09:40:31 +00006702 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006703}
6704
John McCall48871652010-08-21 09:40:31 +00006705void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6706 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006707
Sebastian Redlf769df52009-03-24 22:27:57 +00006708 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6709 if (!Fn) {
6710 Diag(DelLoc, diag::err_deleted_non_function);
6711 return;
6712 }
6713 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6714 Diag(DelLoc, diag::err_deleted_decl_not_first);
6715 Diag(Prev->getLocation(), diag::note_previous_declaration);
6716 // If the declaration wasn't the first, we delete the function anyway for
6717 // recovery.
6718 }
6719 Fn->setDeleted();
6720}
Sebastian Redl4c018662009-04-27 21:33:24 +00006721
6722static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6723 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6724 ++CI) {
6725 Stmt *SubStmt = *CI;
6726 if (!SubStmt)
6727 continue;
6728 if (isa<ReturnStmt>(SubStmt))
6729 Self.Diag(SubStmt->getSourceRange().getBegin(),
6730 diag::err_return_in_constructor_handler);
6731 if (!isa<Expr>(SubStmt))
6732 SearchForReturnInStmt(Self, SubStmt);
6733 }
6734}
6735
6736void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6737 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6738 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6739 SearchForReturnInStmt(*this, Handler);
6740 }
6741}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006742
Mike Stump11289f42009-09-09 15:08:12 +00006743bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006744 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006745 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6746 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006747
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006748 if (Context.hasSameType(NewTy, OldTy) ||
6749 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006750 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006751
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006752 // Check if the return types are covariant
6753 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006754
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006755 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006756 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6757 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006758 NewClassTy = NewPT->getPointeeType();
6759 OldClassTy = OldPT->getPointeeType();
6760 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006761 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6762 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6763 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6764 NewClassTy = NewRT->getPointeeType();
6765 OldClassTy = OldRT->getPointeeType();
6766 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006767 }
6768 }
Mike Stump11289f42009-09-09 15:08:12 +00006769
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006770 // The return types aren't either both pointers or references to a class type.
6771 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006772 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006773 diag::err_different_return_type_for_overriding_virtual_function)
6774 << New->getDeclName() << NewTy << OldTy;
6775 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006776
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006777 return true;
6778 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006779
Anders Carlssone60365b2009-12-31 18:34:24 +00006780 // C++ [class.virtual]p6:
6781 // If the return type of D::f differs from the return type of B::f, the
6782 // class type in the return type of D::f shall be complete at the point of
6783 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006784 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6785 if (!RT->isBeingDefined() &&
6786 RequireCompleteType(New->getLocation(), NewClassTy,
6787 PDiag(diag::err_covariant_return_incomplete)
6788 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006789 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006790 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006791
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006792 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006793 // Check if the new class derives from the old class.
6794 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6795 Diag(New->getLocation(),
6796 diag::err_covariant_return_not_derived)
6797 << New->getDeclName() << NewTy << OldTy;
6798 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6799 return true;
6800 }
Mike Stump11289f42009-09-09 15:08:12 +00006801
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006802 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006803 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006804 diag::err_covariant_return_inaccessible_base,
6805 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6806 // FIXME: Should this point to the return type?
6807 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006808 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6809 return true;
6810 }
6811 }
Mike Stump11289f42009-09-09 15:08:12 +00006812
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006813 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006814 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006815 Diag(New->getLocation(),
6816 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006817 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006818 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6819 return true;
6820 };
Mike Stump11289f42009-09-09 15:08:12 +00006821
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006822
6823 // The new class type must have the same or less qualifiers as the old type.
6824 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6825 Diag(New->getLocation(),
6826 diag::err_covariant_return_type_class_type_more_qualified)
6827 << New->getDeclName() << NewTy << OldTy;
6828 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6829 return true;
6830 };
Mike Stump11289f42009-09-09 15:08:12 +00006831
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006832 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006833}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006834
Alexis Hunt96d5c762009-11-21 08:43:09 +00006835bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6836 const CXXMethodDecl *Old)
6837{
6838 if (Old->hasAttr<FinalAttr>()) {
6839 Diag(New->getLocation(), diag::err_final_function_overridden)
6840 << New->getDeclName();
6841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6842 return true;
6843 }
6844
6845 return false;
6846}
6847
Douglas Gregor21920e372009-12-01 17:24:26 +00006848/// \brief Mark the given method pure.
6849///
6850/// \param Method the method to be marked pure.
6851///
6852/// \param InitRange the source range that covers the "0" initializer.
6853bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6854 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6855 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006856 return false;
6857 }
6858
6859 if (!Method->isInvalidDecl())
6860 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6861 << Method->getDeclName() << InitRange;
6862 return true;
6863}
6864
John McCall1f4ee7b2009-12-19 09:28:58 +00006865/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6866/// an initializer for the out-of-line declaration 'Dcl'. The scope
6867/// is a fresh scope pushed for just this purpose.
6868///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006869/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6870/// static data member of class X, names should be looked up in the scope of
6871/// class X.
John McCall48871652010-08-21 09:40:31 +00006872void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006873 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006874 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006875
John McCall1f4ee7b2009-12-19 09:28:58 +00006876 // We should only get called for declarations with scope specifiers, like:
6877 // int foo::bar;
6878 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006879 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006880}
6881
6882/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006883/// initializer for the out-of-line declaration 'D'.
6884void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006885 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006886 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006887
John McCall1f4ee7b2009-12-19 09:28:58 +00006888 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006889 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006890}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006891
6892/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6893/// C++ if/switch/while/for statement.
6894/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006895DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006896 // C++ 6.4p2:
6897 // The declarator shall not specify a function or an array.
6898 // The type-specifier-seq shall not contain typedef and shall not declare a
6899 // new class or enumeration.
6900 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6901 "Parser allowed 'typedef' as storage class of condition decl.");
6902
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006903 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006904 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6905 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006906
6907 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6908 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6909 // would be created and CXXConditionDeclExpr wants a VarDecl.
6910 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6911 << D.getSourceRange();
6912 return DeclResult();
6913 } else if (OwnedTag && OwnedTag->isDefinition()) {
6914 // The type-specifier-seq shall not declare a new class or enumeration.
6915 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6916 }
6917
John McCall48871652010-08-21 09:40:31 +00006918 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006919 if (!Dcl)
6920 return DeclResult();
6921
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006922 return Dcl;
6923}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006924
Douglas Gregor88d292c2010-05-13 16:44:06 +00006925void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6926 bool DefinitionRequired) {
6927 // Ignore any vtable uses in unevaluated operands or for classes that do
6928 // not have a vtable.
6929 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6930 CurContext->isDependentContext() ||
6931 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006932 return;
6933
Douglas Gregor88d292c2010-05-13 16:44:06 +00006934 // Try to insert this class into the map.
6935 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6936 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6937 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6938 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006939 // If we already had an entry, check to see if we are promoting this vtable
6940 // to required a definition. If so, we need to reappend to the VTableUses
6941 // list, since we may have already processed the first entry.
6942 if (DefinitionRequired && !Pos.first->second) {
6943 Pos.first->second = true;
6944 } else {
6945 // Otherwise, we can early exit.
6946 return;
6947 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006948 }
6949
6950 // Local classes need to have their virtual members marked
6951 // immediately. For all other classes, we mark their virtual members
6952 // at the end of the translation unit.
6953 if (Class->isLocalClass())
6954 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006955 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006956 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006957}
6958
Douglas Gregor88d292c2010-05-13 16:44:06 +00006959bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006960 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006961 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00006962
Douglas Gregor88d292c2010-05-13 16:44:06 +00006963 // Note: The VTableUses vector could grow as a result of marking
6964 // the members of a class as "used", so we check the size each
6965 // time through the loop and prefer indices (with are stable) to
6966 // iterators (which are not).
6967 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006968 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006969 if (!Class)
6970 continue;
6971
6972 SourceLocation Loc = VTableUses[I].second;
6973
6974 // If this class has a key function, but that key function is
6975 // defined in another translation unit, we don't need to emit the
6976 // vtable even though we're using it.
6977 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006978 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006979 switch (KeyFunction->getTemplateSpecializationKind()) {
6980 case TSK_Undeclared:
6981 case TSK_ExplicitSpecialization:
6982 case TSK_ExplicitInstantiationDeclaration:
6983 // The key function is in another translation unit.
6984 continue;
6985
6986 case TSK_ExplicitInstantiationDefinition:
6987 case TSK_ImplicitInstantiation:
6988 // We will be instantiating the key function.
6989 break;
6990 }
6991 } else if (!KeyFunction) {
6992 // If we have a class with no key function that is the subject
6993 // of an explicit instantiation declaration, suppress the
6994 // vtable; it will live with the explicit instantiation
6995 // definition.
6996 bool IsExplicitInstantiationDeclaration
6997 = Class->getTemplateSpecializationKind()
6998 == TSK_ExplicitInstantiationDeclaration;
6999 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7000 REnd = Class->redecls_end();
7001 R != REnd; ++R) {
7002 TemplateSpecializationKind TSK
7003 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7004 if (TSK == TSK_ExplicitInstantiationDeclaration)
7005 IsExplicitInstantiationDeclaration = true;
7006 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7007 IsExplicitInstantiationDeclaration = false;
7008 break;
7009 }
7010 }
7011
7012 if (IsExplicitInstantiationDeclaration)
7013 continue;
7014 }
7015
7016 // Mark all of the virtual members of this class as referenced, so
7017 // that we can build a vtable. Then, tell the AST consumer that a
7018 // vtable for this class is required.
7019 MarkVirtualMembersReferenced(Loc, Class);
7020 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7021 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7022
7023 // Optionally warn if we're emitting a weak vtable.
7024 if (Class->getLinkage() == ExternalLinkage &&
7025 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007026 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007027 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7028 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007029 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007030 VTableUses.clear();
7031
Anders Carlsson82fccd02009-12-07 08:24:59 +00007032 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007033}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007034
Rafael Espindola5b334082010-03-26 00:36:59 +00007035void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7036 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007037 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7038 e = RD->method_end(); i != e; ++i) {
7039 CXXMethodDecl *MD = *i;
7040
7041 // C++ [basic.def.odr]p2:
7042 // [...] A virtual member function is used if it is not pure. [...]
7043 if (MD->isVirtual() && !MD->isPure())
7044 MarkDeclarationReferenced(Loc, MD);
7045 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007046
7047 // Only classes that have virtual bases need a VTT.
7048 if (RD->getNumVBases() == 0)
7049 return;
7050
7051 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7052 e = RD->bases_end(); i != e; ++i) {
7053 const CXXRecordDecl *Base =
7054 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007055 if (Base->getNumVBases() == 0)
7056 continue;
7057 MarkVirtualMembersReferenced(Loc, Base);
7058 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007059}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007060
7061/// SetIvarInitializers - This routine builds initialization ASTs for the
7062/// Objective-C implementation whose ivars need be initialized.
7063void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7064 if (!getLangOptions().CPlusPlus)
7065 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007066 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007067 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7068 CollectIvarsToConstructOrDestruct(OID, ivars);
7069 if (ivars.empty())
7070 return;
7071 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7072 for (unsigned i = 0; i < ivars.size(); i++) {
7073 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007074 if (Field->isInvalidDecl())
7075 continue;
7076
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007077 CXXBaseOrMemberInitializer *Member;
7078 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7079 InitializationKind InitKind =
7080 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7081
7082 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007083 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007084 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007085 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007086 // Note, MemberInit could actually come back empty if no initialization
7087 // is required (e.g., because it would call a trivial default constructor)
7088 if (!MemberInit.get() || MemberInit.isInvalid())
7089 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007090
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007091 Member =
7092 new (Context) CXXBaseOrMemberInitializer(Context,
7093 Field, SourceLocation(),
7094 SourceLocation(),
7095 MemberInit.takeAs<Expr>(),
7096 SourceLocation());
7097 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007098
7099 // Be sure that the destructor is accessible and is marked as referenced.
7100 if (const RecordType *RecordTy
7101 = Context.getBaseElementType(Field->getType())
7102 ->getAs<RecordType>()) {
7103 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007104 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007105 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7106 CheckDestructorAccess(Field->getLocation(), Destructor,
7107 PDiag(diag::err_access_dtor_ivar)
7108 << Context.getBaseElementType(Field->getType()));
7109 }
7110 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007111 }
7112 ObjCImplementation->setIvarInitializers(Context,
7113 AllToInit.data(), AllToInit.size());
7114 }
7115}